Ask Your Question

Revision history [back]

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 \ \text{ if } -2 \leq x \leq 0, \quad g(x) = 1-x \ \text{ if } 0 \leq x \leq 2$$ and then require $g$ to be periodic with period 4. Then McCarthy's function is $$f(x) = \sum_{n=1}^{\infty} 2^{-n} g(2^{2^{n}} x).$$

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?

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 \ \text{ if } -2 \leq x \leq 0, \quad g(x) = 1-x \ \text{ if } 0 \leq x \leq 2$$ and then require $g$ to be periodic with period 4. Then McCarthy's function is $$f(x) = \sum_{n=1}^{\infty} 2^{-n} g(2^{2^{n}} x).$$

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?