使用 pgfplots 绘制傅里叶展开

使用 pgfplots 绘制傅里叶展开

我需要绘制 M = 16 的情况: 在此处输入图片描述

不幸的是,我这样做的方式似乎完全错误:

\documentclass{article}
\usepackage{tikz}
\usepackage{pgfplots}

\begin{document}
\begin{figure}[h] \label{fig:csm:graph}
    \centering
    \begin{tikzpicture}
        \begin{axis}[axis lines = middle, xlabel = $d - z$, ylabel = $I$]
            \def\sum{0}
            \pgfplotsinvokeforeach{1, 2,..., 16}{
                \def\ck{pi * (2 * #1 - 1)}
                \xdef\sum{\sum + (1 / \ck) * sin(\ck * x)}
            }
            \xdef\sum{2 * \sum + 0.5}
            \addplot[domain = -0.5:1, red] (x, {\sum});
        \end{axis}
    \end{tikzpicture}
\end{figure}
\end{document}

任何帮助将非常感激。

编辑:添加 MWE。

答案1

对于更复杂的数学运算,LaTeX 并不是合适的工具。使用名为 Sage 的计算机代数系统,通过(免费)萨基马云帐户,您就可以快速获得您的地块。

\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}

输出结果如下:在此处输入图片描述 使用 Sage,您必须告诉它您正在逼近的函数(在您的例子中是 1 和 0 的分段函数),Sage 会处理其余部分 - 这是绘制的第二幅图(使用 # 上方的代码)。使用 pgfplots,您必须构建函数(这是 # 下方大多数代码的作用)。Python 不会执行最后一个数字,因此循环实际上转到 16,而不是 17。

相关内容