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 −2≤x≤0,g(x)=1−x if 0≤x≤2 and then require g to be periodic with period 4. Then McCarthy's function is f(x)=∞∑n=12−ng(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?