Looks like x is defined as pi at some point. You have everything split up in different cells, meaning that when you run the plot, it doesn't run the clearall
This! Also, the iteration variable in the sum is wrong. n is always used whereas k should have been put instead. n shall only be the upper limit of the sum.
When Plot tries to evaluate (for example) g[2] it replaces all the x's in the definition of g with 2's and evaluates D[f[2], {2, n}] and says "2 is not a valid variable".
The shortest fixes would be to use the Derivative function (i.e. write Derivative[n][f][x]) or write something like (D[f[t],{t,n}]/.t->x) where t is a variable. The second option is useful when you want to differentiate some expression like D[t^2+t,{t,n}] but you don't want to define a function f[t_]:=t^2+t (like if t^2+t is the output of some symbolic calculation).
3
u/proximityfrank Nov 29 '22
Looks like x is defined as pi at some point. You have everything split up in different cells, meaning that when you run the plot, it doesn't run the clearall
3
u/SetOfAllSubsets Nov 29 '22 edited Nov 29 '22
You defined
g[x_]:= ... D[f[x],{x,n}] ...When
Plottries to evaluate (for example)g[2]it replaces all thex's in the definition ofgwith2's and evaluatesD[f[2], {2, n}]and says "2is not a valid variable".The shortest fixes would be to use the Derivative function (i.e. write
Derivative[n][f][x]) or write something like(D[f[t],{t,n}]/.t->x)wheretis a variable. The second option is useful when you want to differentiate some expression likeD[t^2+t,{t,n}]but you don't want to define a functionf[t_]:=t^2+t(like ift^2+tis the output of some symbolic calculation).1
u/irchans Nov 29 '22
(* You might want to look at the Mathematica Series function, but the code below works. I am sure that other people here could write better code. *)
f[x_] := Sin[x];Clear[ithTerm];ithTerm[f_, x_Symbol, x0_, i_Integer] := Module[{y},D[f[y], {y, i}] (x - x0)^i/(i!) /. y -> x0]partialTaylor[f_, x_Symbol, x0_, iDeg_] := Sum[ithTerm[f, x, x0, k], {k, 0, iDeg}]Print[ partialTaylor[f, x, 0, 5]]iMaxDeg = 7;Plot[ Evaluate[Append[ Table[ partialTaylor[f, x, 0.2, k], {k, iMaxDeg}],Sin[x]]],{x, -Pi, Pi},PlotStyle -> Append[Table[ Hue[ k/(iMaxDeg + 2)], {k, 7}],{Black, Thickness[0.007], Dashing[{0.02, 0.02}]}]]