How can I evaluate an integration to a number?
I have some functions set up like this:
f(x):=1-2**-x$
g(y):=integrate(f(x), x, 0, y)$
and evaluated them:
f(1)$float(%);
g(1)$float(%);
but for g(1), I got a symbolic answer instead of a numerical answer开发者_运维知识库. Using float() was an attempt to get a numerical answer but it just turned all of the terms in the integral into floats.
How can I get g(1) as a number?
Why not just do (by the definition of definite integral):
f(x):=1-2**-x$
gg(x):=''(integrate(f(x), x))$
g(y):=gg(y) - gg(0)$
'' (quote-quote) operator is used to force the evaluation of the :='s right hand side before the assignment.
If you're only interested in a numerical solution, then you could use numerical integration.
For example you could use quad_qag (f(x), x, a, b, key, [epsrel, epsabs, limit])
.
I tried:
f(x) := 1-2^(-x);
g(y):= quad_qag(f(x), x, 0, y, 3, epsrel=10d-8)$
g(1);
which returns:
[0.27865247955552,3.093663986714272*10^-15,31,0]
the first entry is the numerical solution,
the second entry is the approximate relative error,
the third entry is the number of iterations required to achieve the solution,
and the last entry is an error code; error codes are
- 0 if no problems were encountered;
- 1 if too many sub-intervals were done;
- 2 if excessive roundoff error is detected;
- 3 if extremely bad integrand behavior occurs;
- 6 if the input is invalid.
BTW, the exact solution is 1-1/(2*log(2)) which is approximately 0.27865.
精彩评论