# creating a fourier series animation

Hello, I want to create an animation of sum((-1)^(n-1)sin(nx)/n,n,1 , k)

and show that as the number of terms 'k' in the partial sums increase, the sum converges to x/2 i.e looks more and more like the graph of x/2.

My first try is

a = animate([(sum((-1)^(n-1)sin(nx)/n,n,1 , k))] for k in range (1,50,1))

But that returns me an error

Traceback (click to the left of this block for traceback) ... AttributeError: 'int' object has no attribute '_maxima_'

Also I want to include a static graph of x/2 in the background of the animation so that it is easy to observe that the series converges to x/2. how to do this?

edit retag close merge delete

Sort by » oldest newest most voted

As for the AttributeError, that's happening because the range function returns Python ints and the function expects Sage Integers. They're slightly different types, with different behaviour; usually in Sage you want Integers, so I seldom use range myself when writing Sage code. You can replace range with any of srange, xsrange, sxrange, IntegerRange, or write (1..49) instead to fix it, anything which returns an Integer.

[It should probably be considered a bug that this doesn't happen automatically here.]

To put a line in the background, though, I think it's easiest to forget that the animate command accepts functions and treat it merely as a tool to join plots together. That is, first you want to make the plots that you want, and then get animate to combine them. You can use the animate coercion as a shortcut sometimes, but when you try to start adding extra features it's much easier to work with plots as normal.

For example, something like:

n = var("n")
frames = []
xr = (x, 0, 1)
for k in srange(1, 50):
g = plot((sum((-1)^(n-1)*sin(n*x)/n,n,1,k)), xr, color="blue", legend_label='k = %d' % k)
g += plot(x/2, xr, color="green", legend_label="x/2")
frames.append(g)

a = animate(frames, ymin=0.0, ymax=1.0, legend_loc=(0.2,0.8))
a.show()


You could do the above in two lines if you really wanted to, but I think the above is clearer and more easily extensible.

more

it works so well! thanks:)

( 2011-04-10 02:01:53 -0500 )edit

when I type your code into sage, I get this error. how do I fix this?

Traceback (click to the left of this block for traceback) ... TypeError: unsupported operand parent(s) for '-': '<type 'function'="">' and 'Integer Ring'

how do I fix this?

more

Ah, sorry! I forgot that I'd redefined "n" as a variable; I've corrected the original. By the way, if you're replying to an answer, usually we enter it using the "post a comment" button.

( 2011-04-09 06:22:48 -0500 )edit