67
294
5 Array computing and curve plotting
Hint 2. The velocity vector is
(
dx
dt
,
dy
dt
)= (−ωa sin(ωt),ωb cos(ωt)),
and the magnitude of this vector becomes ω
�
a2 sin2(ωt) + b2 cos2(ωt).
Filename: planet_orbit.py.
Exercise 5.37: Animate the evolution of Taylor polynomials
Ageneral series approximation (to a function) can be written as
S(x;M,N) =
�N
k=M
f
k
(x) .
For example, the Taylor polynomial of degreeN fore
x
equalsS(x;0,N )
withf
k
(x) =xk/k!. The purpose of the exercise is to make a movie of
howS(x;M,N) develops and improves as an approximation as we add
terms in the sum. That is, the frames in the movie correspond to plots
of S(x;M,M ), S(x; M, M + 1), S(x;M,M + 2), . .., S(x; M, N).
a) Make a function
animate_series(fk, M, N, xmin, xmax, ymin, ymax, n, exact)
for creating such animations. The argumentfk holds a Python function
implementing the termf
k
(x) in the sum,M andN are the summation
limits, the next arguments are the minimum and maximumx andy
values in the plot,n is the number ofx points in the curves to be plotted,
and exact holds the function that S(x) aims at approximating.
Hint. Here is s some more information on n how to o write e the
animate_series function. The function n must accumulate e the f
k
(x)
terms in a variables, and for eachk value,s is plotted againstx together
with a curve reflecting the exact function. Each plot must be saved in
afile, say with namestmp_0000.png,tmp_0001.png, and so on (these
filenames can be generated by tmp_%04d.png, using an appropriate
counter). Use themovie function to combine all the plot files into a
movie in a desired movie format.
In the beginning of theanimate_series function, it is necessary to
remove all old plot files of the formtmp_*.png. This can be done by the
globmoduleandtheos.removefunctionasexemplifiedinSection5.3.4.
b) Call the animate_series s function for r the Taylor r seriesfor sinx,
wheref
k
(x) = (−1)
k
x
2k+1
/(2k + 1)!,and x ∈[0 ,13π], M=0,N=40,
y∈ [−2, 2].
c)Calltheanimate_seriesfunctionfortheTaylorseriesfor e−x,where
f
k
(x) = (−x)k/k!, and x ∈ [0,15], M = 0, N = 30, y ∈ [−0.5,1.4].
Filename: animate_Taylor_series.py.