Ask Your Question
0

Plotting a recursive function

asked 2013-01-22 01:07:02 +0200

propterhoc gravatar image

updated 2013-01-22 18:59:01 +0200

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 flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
3

answered 2013-01-22 02:24:52 +0200

benjaminfjones gravatar image

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

edit flag offensive delete link more

Comments

1

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

propterhoc gravatar imagepropterhoc ( 2013-01-22 18:56:27 +0200 )edit

I also fixed the indentation.

propterhoc gravatar imagepropterhoc ( 2013-01-22 18:59:24 +0200 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2013-01-22 01:07:02 +0200

Seen: 1,406 times

Last updated: Jan 22 '13