Processing math: 100%
Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

defining periodic functions

I'm trying to plot approximations to McCarthy's continuous nowhere differentiable function (PDF file). The definition is like this: first, define a function g(x) to be a triangle wave: g(x)=1+x  if 2x0,g(x)=1x  if 0x2 and then require g to be periodic with period 4. Then McCarthy's function is f(x)=n=12ng(22nx).

How should I set this up in Sage? If I define g(x) by

def g(x):
    if -2 <= x and x <= 0:
        return 1+x
    elif 0 < x and x <= 2:
        return 1-x
    elif x > 2:
        return g(x-4)
    return g(x+4)

and then try to plot the 4th partial sum for f(x), I get an error about "maximum recursion depth exceeded". I get the same error if I try plot(g, (x, 10000, 10010)). Is there a better way of defining a periodic function like g? I guess I can do something like while x>2: x = x-4, etc., but my real question is, can I define such a function symbolically rather than as a Python function?

click to hide/show revision 2
No.2 Revision

defining periodic functions

I'm trying to plot approximations to McCarthy's continuous nowhere differentiable function (PDF file). The definition is like this: first, define a function g(x) to be a triangle wave: g(x)=1+x  if 2x0,g(x)=1x  if 0x2 and then require g to be periodic with period 4. Then McCarthy's function is f(x)=n=12ng(22nx).

How should I set this up in Sage? If I define g(x) by

def g(x):
    if -2 <= x and x <= 0:
        return 1+x
    elif 0 < x and x <= 2:
        return 1-x
    elif x > 2:
        return g(x-4)
    return g(x+4)

and then try to plot the 4th partial sum for f(x), I get an error about "maximum recursion depth exceeded". I get the same error if I try plot(g, (x, 10000, 10010)). Is there a better way of defining a periodic function like g? I guess I can do something like while x>2: x = x-4, etc., but my real question is, can I define such a function symbolically rather than as a Python function?

Edit: my current fastest version of this function is as follows:

%cython
def g(float x):
    x = abs(x)
    x = 4.0*(x/4.0 - int(x/4.0))
    if x <= 2:
        return 1-x
    return -3+x

Even if it's not possible to write this symbolically, how can I speed this up?