Ask Your Question

propterhoc's profile - activity

2014-06-29 06:56:34 +0200 received badge  Notable Question (source)
2014-06-29 06:56:34 +0200 received badge  Famous Question (source)
2014-02-04 18:54:40 +0200 received badge  Popular Question (source)
2013-01-22 18:59:38 +0200 received badge  Scholar (source)
2013-01-22 18:59:38 +0200 marked best answer Plotting a recursive function

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))

See http://aleph.sagemath.org/?q=79243f15...

2013-01-22 18:59:24 +0200 commented answer Plotting a recursive function

I also fixed the indentation.

2013-01-22 18:56:27 +0200 commented answer Plotting a recursive function

Thank you! This is exactly what I was trying to do.

2013-01-22 01:11:45 +0200 received badge  Supporter (source)
2013-01-22 01:09:43 +0200 received badge  Editor (source)
2013-01-22 01:07:02 +0200 asked a question 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.