nval
Numerically evaluate expressions
\available{2.5.12}
By default Cadabra does not evaluate integrals, neither symbolically nor numerically. If you want to replace an integral with its numerical value, use nval
(for symbolic evaluation, consult integrate
instead).
This function will in future versions be extended to handle other numerical evaluations (e.g. sums) as well.The example below shows the basic usage of
nval
:ex:= \int{ \sin(x)/\sqrt{x+3} }{x, 0, 1};
\(\displaystyle{}\int_{0\,}^{1} \sin{x} {\left(x +3\,\right)}^{ - \frac{1}{2}\,}\,\,{\rm d}x\)
nval(_);
\(\displaystyle{}0.240842\,\)
Note how this has change the original expression:
ex;
\(\displaystyle{}0.240842\,\)
You can pass an optional dict of values for parameters in the expression. The values passed here must be numerical (so if you want to use e.g. $\pi$, use
np.pi
for now). In the following example we have an integral which depends on a parameter $a$,ex:= \int{ \sin(x) }{x, 0, a};
\(\displaystyle{}\int_{0\,}^{a} \sin{x}\,\,{\rm d}x\)
We can evaluate this for $a=2$ by passing that value into
nval
,nval(ex, {$a$: 2} );
\(\displaystyle{}1.41615\,\)
If you want to evaluate only a certain part of your expression numerically, first zoom in to that part before you call
nval
. In the example below, we initially want to evaluate the integral containing the sine, but not the one containing the cosine.ex:= \int{\sin(x)}{x,0,\pi} + \int{\cos(x)**2}{x,0,\pi};
\(\displaystyle{}\int_{0\,}^{\pi} \sin{x}\,\,{\rm d}x +\int_{0\,}^{\pi} {\left(\cos{x}\right)}^{2\,}\,\,{\rm d}x\)
zoom(_, $\int{\sin{A??}}{B??}$);
\(\displaystyle{}\int_{0\,}^{\pi} \sin{x}\,\,{\rm d}x + ... \)
nval(_);
\(\displaystyle{}2\, + ... \)
unzoom(_);
\(\displaystyle{}2\, +\int_{0\,}^{\pi} {\left(\cos{x}\right)}^{2\,}\,\,{\rm d}x\)
If you now still want to evaluate the cosine integral too, you can call
nval
on the full, unzoomed expression,nval(_);
\(\displaystyle{}3.5708\,\)
While the integration variable has to be real,
nval
function can deal with complex-valued integrandsi::ImaginaryI;
ex:= A \int{ \exp{i x} }{x, 0, \pi};
nval(_);
\(\displaystyle{}\text{Property ImaginaryI attached to }i.\)
\(\displaystyle{}A \int_{0\,}^{\pi} \exp\left(i x\right)\,\,{\rm d}x\)
\(\displaystyle{}A (1.1847 \times 10^{-16} + 2i)\)
Under the hood, the numerical integration method used is Gauss-Kronrod, which does not (yet) deal with infinite or semi-infinite integration ranges.