How can I use the pgf
maths engine to plot the integral of any function?
For example \addplot {int(cos(x))}
does not work.
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It only takes a minute to sign up.
Sign up to join this communityHow can I use the pgf
maths engine to plot the integral of any function?
For example \addplot {int(cos(x))}
does not work.
As was said in the comments, you PGF can't compute the antiderivative analytically. If the function is reasonably linear, you can quite easily compute the antiderivative numerically, similar to the approach in Get derivative of a function.
Here's an approach using PGFPlotstable to calculate the function values:
\documentclass[border=5mm]{article}
\usepackage{pgfplots, pgfplotstable}
\pgfplotstablenew[
create on use/x/.style={
create col/expr={\pgfplotstablerow/50}
},
create on use/y/.style={
create col/expr={cos(deg(\thisrow{x}))}
},
create on use/int/.style={
create col/expr={\pgfmathaccuma+(\thisrow{y}+\prevrow{y})/2*(\thisrow{x}-\prevrow{x})}
},
columns={x,y,int}
]
{200}
\datatableA
\begin{document}
\begin{tikzpicture}[trim axis left]
\begin{axis}[no markers, legend style={at={(0.5,-0.20)}, anchor=north}, legend entries={Original function, Analytical antiderivative, Numerical antiderivative}]
\addplot [gray] table {\datatableA};
\addplot [line width=3pt, red!50, domain=0:4] {sin(deg(x))};
\addplot [black] table [y=int] {\datatableA};
\end{axis}
\end{tikzpicture}\\[3ex]
\pgfplotstablenew[
create on use/x/.style={
create col/expr={\pgfplotstablerow/50-2}
},
create on use/y/.style={
create col/expr={\thisrow{x}^3}
},
create on use/int/.style={
create col/expr={\pgfmathaccuma+(\thisrow{y}+\prevrow{y})/2*(\thisrow{x}-\prevrow{x})}
},
columns={x,y,int}
]
{200}
\datatableB
\begin{tikzpicture}[trim axis left]
\begin{axis}[no markers, samples=500]
\addplot [gray] table {\datatableB};
\addplot [line width=3pt, red!50, domain=-2:2] {1/4*x^4};
\addplot [black] table [y expr=\thisrow{int}-4] {\datatableB};
\end{axis}
\end{tikzpicture}
\end{document}
\addplot[int] {cos(deg(x))};
(that is automatic definition of the function to be used in the table and \addplot table
behind the scene)?
pgfmath
so that it could parse something like int(cos(deg(x)),x,0,1)
.
Mar 21, 2013 at 12:28
PSTricks can do it. Here is an example for the default Simpson method (Integral of sin(x)+cos(x):
\documentclass[pstricks,border=15pt]{standalone}
\usepackage{pst-func}
\begin{document}
\begin{pspicture}[linewidth=1pt](-1,-1.5)(7,2.5)
\psaxes{->}(0,0)(-1,-1.2)(6.75,2.5)
\psplot[linecolor=red,algebraic]{0}{6.5}{cos(x)+sin(x)}
\psCumIntegral[plotpoints=500,Simpson=10,
linecolor=blue]{0}{6.5}{ RadtoDeg dup cos exch sin add }
\end{pspicture}
\end{document}
Run it with xelatex
. pst-func
also knows \psIntegral
, see documentation.
\pgfplotsforeachungrouped
. Symbolic integration, though, is a different problem altogether.