# Plotting a recursive function

I'm trying to plot different iterations of the Cantor function using the iterative definition:

Let 0(x) = x.

Then,

Let n+1(x) = 1/2*n(3x), when 0 <= x < 1/3;

Let n+1(x) = 1/2, when 1/3 <= x < 2/3;

Let n+1(x) = 1/2 + 1/2*n(3x - 2), when 2/3 <= x <= 1.

I extended it to be 0 when x<0 and 1 when x>1.

The function I have defined returns the correct values for a specific iteration and a specific x, but it is not plotting how I would like it to. When I plot it, I just get a horizontal line at 1.

def cantor(z,iter=0):
#'z' is the x value
#'iter' is the number of iterations in the iterative process
if iter == 0:
val = z
elif z<0:
val = 0
elif z<(1/3):
val = (1/2)*cantor(3*z,iter-1)
elif z<=(2/3):
val = (1/2)
elif z<=1:
val = (1/2)+(1/2)*cantor(3*z-2,iter-1)
else:
val = 1
return val

plot(cantor(x,0)) #this works
plot(cantor(x,1)) #this doesn't work


Thanks in advance for any help.

edit retag close merge delete

Sort by » oldest newest most voted

First, your indentation is messed up, but that's probably just a formatting problem in your question.

The real issue is that when cantor(x,0) is evaluated, x refers to the symbolic variable, so all of your conditions like z < 0 are False (Sage can't prove they are True because it doesn't know anything specific about x) and execution falls through to the default val = 1. That's why you get a horizontal line at $y=1$.

If you replace the expression cantor(x,0) with an anonymous function that delays evaluation of cantor you'll get what you expect:

def cantor(z,iter=0):
#'z' is the x value
#'iter' is the number of iterations in the iterative process
if iter == 0:
val = z
elif z<0:
val = 0
elif z<(1/3):
val = (1/2)*cantor(3*z,iter-1)
elif z<=(2/3):
val = (1/2)
elif z<=1:
val = (1/2)+(1/2)*cantor(3*z-2,iter-1)
else:
val = 1
return val

plot(lambda x: cantor(x,1))

more

1