For more complicated math, LaTeX is not the proper tool. Using a computer algebra system called Sage, running through a (free) Sagemath Cloud account you can quickly get your plots.
\documentclass{article}
\usepackage{sagetex}
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage{pgfplots}
\begin{document}
\begin{sagesilent}
t = var('t')
x = var('x')
f1 = lambda t: 1
f2 = lambda t: 0
f = Piecewise([[(-1,0),f1],[(0,1),f2]])
Fourier=f.plot_fourier_series_partial_sum(32,1,-.5,.5)
############################
LowerY = -.2
UpperY = 1.2
LowerX = -.5
UpperX = .5
step = .005
g =.5
for i in range(1,17):
g += -2*(1/(pi*(2*i-1)))*sin((pi*(2*i-1))*x)
x_coords = [t for t in srange(LowerX,UpperX,step)]
y_coords = [g(t).n(digits=6) for t in srange(LowerX,UpperX,step)]
output = r""
output += r"\begin{tikzpicture}[scale=.7]"
output += r"\begin{axis}[xmin=%f,xmax=%f,ymin= %f,ymax=%f]"% (LowerX,UpperX,LowerY, UpperY)
output += r"\addplot[thin, blue, unbounded coords=jump] coordinates {"
for i in range(0,len(x_coords)-1):
if (y_coords[i])<LowerY or (y_coords[i])>UpperY:
output += r"(%f , inf) "%(x_coords[i])
else:
output += r"(%f , %f) "%(x_coords[i],y_coords[i])
output += r"};"
output += r"\end{axis}"
output += r"\end{tikzpicture}"
\end{sagesilent}
\begin{center}
\sagestr{output}
\end{center}
\begin{center}
\sageplot[width=6cm]{plot(Fourier, (x, -.5, .5),ymin=-.2, ymax=1.2,detect_poles=True)}
\end{center}
\end{document}
Resulting in this output:
Using Sage, you have to tell it the function you're approximating (in your case the piece-wise function of 1 and 0) and Sage takes care of the rest-- that's the second picture plotted (using the code above the #'s). Using pgfplots you have to build the function (which is what most of the code below the #'s is doing). Python doesn't execute the last number, hence the loop really goes to 16, not 17.
\documentclass{...}
and ending with\end{document}
.\sum
or you'll not be able to use the symbol in math formulas. Substitute with\SUM
or anything else.tikz
expert, but I wonder if the calculation in the loop is actually updating the\sum
(by the way,\sum
is LaTeX macro 'reserved' for other purposes) -- just checked. It does no calculation of course!sin
expects its argument in degrees, so you have to usesin(deg(\ck * x))
and also to increase the number of samples.pgfplotstable