Matlab cannot compute an infinite integral? - matlab

I am studying Stochastic calculus, and occasionally we need to compute an integral (from -infinity to +infinity) for some complex distribution. In this case, it was
with the answer on the right. This is the code I put into Matlab (and I have the symbolic math toolbox), which Matlab simply cannot process:
>> syms x t
>> f = exp(1+2*x)*(1/((2*pi*t)^0.5))*exp(-(x^2)/(2*t))
>> int(f,-inf,inf)
ans =
-((2^(1/2)*pi^(1/2)*exp(2*t + 1)*limit(erf((2^(1/2)*((x*1i)/t - 2i))/(2*(-1/t)^(1/2))), x, -Inf)*1i)/(2*(-1/t)^(1/2)) - (2^(1/2)*pi^(1/2)*exp(2*t + 1)*limit(erf((2^(1/2)*((x*1i)/t - 2i))/(2*(-1/t)^(1/2))), x, Inf)*1i)/(2*(-1/t)^(1/2)))/(2*pi*t)^(1/2)
This answer at the end looks like nonsense, while Wolfram (via their free tool), gives me the answer that the picture above has. Am I missing something fundamental about doing such integrations in Matlab that the basic Mathworks pages don't cover? Where am I proceeding incorrectly?

In order to explain what is happening, we need some theory:
Symbolic systems such as Matlab or Mathematica calculate integrals symbolically by the Risch algorithm (yes, there is a method to mechanically calculate integrals, just like derivatives).
However, the Risch algorithms works differently than using derivation rules. Strictly spoken, it is not an algorithm but a semi-algorithm. This is, it is not deterministic one (as algorithms are).
This (semi) algorithm makes a series of transformations on the input expression (the one to be integrated), and in a specific point, it requires to ask if the transformed expression is equals to zero, because if it were zero, it cannot continue (the input is not integrable using a finite set of terms).
The problem (and the reason of the "semi-algoritmicity") is that, the (apparently simple) equation:
E = 0
Is indecidable (it is also called the constant problem). It means that there cannot exist a formal method to solve the constant problem, for any expression E. Of course, we know to solve the constant problem for specific forms of the expression E (i.e. polynomials), but it is impossible to solve the problem for the general case.
It also means that the Risch algorithm cannot be perfect (being able to solve any integral -integrable in finite terms-). In other words, the Risch algorithm will be as powerful as our ability to solve the constant problem for as many forms of the expression E as we can, but losing any hope of solving for the general case.
Different symbolic systems have similar, but different methods to try to solve equations (and therefore the constant problem), it explains why some of them can "solve" different sets of integrals than others.
And generalizing, because no symbolic system will never be able to solve the constant problem for the general case, it will neither be able to solve any integral (integrable in finite terms).

The second parameter of int() needs to be the variable you're integrating over (which looks like t in this case):
syms x t
f = exp(1+2*x)*(1/((2*pi*t)^0.5))*exp(-(x^2)/(2*t))
int(f,'t',-inf,inf) % <- integrate over t

Related

Is there a way to define a general function in matlab?

Matlab has functionalities that allow you to work with known functions that you must define.
But, sometimes I want to do a complex symbolic calculation using a general function, Say A(x), without specifying A(x).
In other words, is it possible for me to make a statement like
diff(A(x^2+1),x), where the answer should involve a symbolic derivative of A???
diff(A(x^2+1),x) = A' diff(x^2+1,x)
That is, if A' is the derivative of A.
Yes. The functionality you describe is part of the symbolic algebra toolkit -- note that it comes with some fairly significant limitations, but, in short, all you would require would be
syms x A(x)
diff(A(x), x)
Note that ' is reserved for transpose, even with symbolic functions. (Although, personally, I'd frankly suggest Mathematica for any serious symbolic algebra any day over matlab -- it's really the intended purpose of the whole product, whereas the symbolic algebra toolkit is exactly that: a toolkit add-on to the core features of Matlab, namely fast linear algebra).

Matlab's `inv` function [duplicate]

I read at a few places (in the doc and in this blog post : http://blogs.mathworks.com/loren/2007/05/16/purpose-of-inv/ ) that the use of inv in Matlab is not recommended because it is slow and inaccurate.
I am trying to find the reason of this inaccuracy. As of now, Google did not give m interesting result, so I thought someone here could guide me.
Thanks !
The inaccuracy I mentioned is with the method INV, not MATLAB's implementation of it. You should be using QR, LU, or other methods to solve systems of equations since these methods don't typically require squaring the condition number of the system in question. Using inv typically requires an operation that loses accuracy by squaring the condition number of the original system.
--Loren
I think the point of Loren's blog is not that MATLAB's inv function is particularly slower or more inaccurate than any other numerical implementation of computing a matrix inverse; rather, that in most cases the inverse itself is not needed, and you can proceed by other means (such as solving a linear system using \ - the backslash operator - rather than computing an inverse).
inv() is certainly slower than \ unless you have multiple right hand side vectors to solve for. However, the advice from MathWorks regarding inaccuracy is due to a overly conservative bound in a numerical linear algebra result. In other words, inv() is NOT inaccurate. The link elaborates further : http://arxiv.org/abs/1201.6035
Several widely-used textbooks lead the reader to believe that solving a linear system of equations Ax = b by multiplying the vector b by a computed inverse inv(A) is inaccurate. Virtually all other textbooks on numerical analysis and numerical linear algebra advise against using computed inverses without stating whether this is accurate or not. In fact, under reasonable assumptions on how the inverse is computed, x = inv(A)*b is as accurate as the solution computed by the best backward-stable solvers.

Find complex roots from a nonlinear equation

I need to find the roots from the equations as follows (Mathematica):
Sqrt[3]/2*x-(I-x*Sqrt[3]/2*c^2)*I/Sqrt[2*Pi]/d^3*Integrate[t*Exp[-t^2/2/d^2]/(Sqrt[3]/2*x+I*(t+b0)),{t,-Inf,Inf}]=0
i.e. as the picture shows:
where c, d, and b0 is given parameters, x is a complex root needs to find.
I have tried several methods, including scanning the real and imagine part of x and the iteration approach, but non of them could resolve all the cases.
Are there any general approaches that could solve such kind of equation efficiently, or by MATLAB/Mathematica?
did you try Matlab's mupad? it is a powerful symbolic tool, very similar to Maple wich gives really good results in non-numerical mathematics. Try there. declare the equation, give assumptions to the software ,i.e assume c real positive (don't copy this, I dont remember the proper syntax) and then solve! It will very likely find a solution if it exits (sometimes in some mathematical cases that you even don't know!)

Integration with matlab

i want to solve this problem:
alt text http://img265.imageshack.us/img265/6598/greenshot20100727091025.png
i don't want to use "int", i want to use "quad" family (quad,dblquad,triplequad)
but i can't.
can you help me?
I assume that your real problem is more complex than this trivial one. The best solution is just to use a symbolic integral. Why is numerical integration difficult?
Numerical integration in ONE dimension typically requires on the order of say 100 function evaluations. (The exact number will be very dependent on the accuracy required, the limits, etc.) This makes a 2-d integral typically require on the order of 100^2 = 10000 function evals. So an adaptive, 5-d integral will require on the order of 100^5 = 1e10 function evaluations. (This is only a very rough order of magnitude estimate here.) My point is, you simply don't want to do that!
Better is to reduce the problem in complexity. If your integral is separable (as is this one) then do so! Reduce a 5-d problem into multiple 1-d problems.
Also, in many cases I see people wanting to do a numerical integration of a Gaussian PDF. See that this is easily solved using a call to erf or erfc, coupled with a transformation. The point is that in many cases special functions are defined to greatly reduce the complexity of a problem.
I should add that in many cases, the key to solving a difficult problem in mathematics is to use mathematics to reduce the problem to something simpler. If you can find a way to reduce the dimensionality of your problem just a bit, it will become much more tractable.
The integral you show is
Analytically solvable: always do analytically what you can
?equal to a number: constant expressions should be eliminated from numerical calculations
not easy to get calculated in MATLAB (or very correct).
You can use cumtrapz to integrate over each variable alone, and call trapz the final integration. Remember that this will blow up the error on any problem that is more complicated than the simple sum of linear functions.
Mathematica is more suited to nD integrations, if you have access to that.
matlab can do symbolic integration
>> x = sym('x'); y = sym('y'); z = sym('z'); u = sym('u'); v = sym('v');
>> int(int(int(int(int(x+y+z+u+v,1,5),-2,3),0,1),-1,1),0,1)
ans =
180
Just noticed you want to do numeric, not symbolic integration
If you look at the source of dblquad and triplequad
>> edit dblquad
you see that they just call the lower versions.
it should be possible for you to add a quadquad and a quintquad (or recursively an n-quad)

Looking for ODE integrator/solver with a relaxed attitude to derivative precision

I have a system of (first order) ODEs with fairly expensive to compute derivatives.
However, the derivatives can be computed considerably cheaper to within given error bounds, either because the derivatives are computed from a convergent series and bounds can be placed on the maximum contribution from dropped terms, or through use of precomputed range information stored in kd-tree/octree lookup tables.
Unfortunately, I haven't been able to find any general ODE solvers which can benefit from this; they all seem to just give you coordinates and want an exact result back. (Mind you, I'm no expert on ODEs; I'm familiar with Runge-Kutta, the material in the Numerical Recipies book, LSODE and the Gnu Scientific Library's solver).
ie for all the solvers I've seen, you provide a derivs callback function accepting a t and an array of x, and returning an array of dx/dt back; but ideally I'm looking for one which gives the callback t, xs, and an array of acceptable errors, and receives dx/dt_min and dx/dt_max arrays back, with the derivative range guaranteed to be within the required precision. (There are probably numerous equally useful variations possible).
Any pointers to solvers which are designed with this sort of thing in mind, or alternative approaches to the problem (I can't believe I'm the first person wanting something like this) would be greatly appreciated.
Roughly speaking, if you know f' up to absolute error eps, and integrate from x0 to x1, the error of the integral coming from the error in the derivative is going to be <= eps*(x1 - x0). There is also discretization error, coming from your ODE solver. Consider how big eps*(x1 - x0) can be for you and feed the ODE solver with f' values computed with error <= eps.
I'm not sure this is a well-posed question.
In many algorithms, e.g, nonlinear equation solving, f(x) = 0, an estimate of a derivative f'(x) is all that's required for use in something like Newton's method since you only need to go in the "general direction" of the answer.
However, in this case, the derivative is a primary part of the (ODE) equation you're solving - get the derivative wrong, and you'll just get the wrong answer; it's like trying to solve f(x) = 0 with only an approximation for f(x).
As another answer has suggested, if you set up your ODE as applied f(x) + g(x) where g(x) is an error term, you should be able to relate errors in your derivatives to errors in your inputs.
Having thought about this some more, it occurred to me that interval arithmetic is probably key. My derivs function basically returns intervals. An integrator using interval arithmetic would maintain x's as intervals. All I'm interested in is obtaining a sufficiently small error bound on the xs at a final t. An obvious approach would be to iteratively re-integrate, improving the quality of the sample introducing the most error each iteration until we finally get a result with acceptable bounds (although that sounds like it could be a "cure worse than the disease" with regards to overall efficiency). I suspect adaptive step size control could fit in nicely in such a scheme, with step size chosen to keep the "implicit" discretization error comparable with the "explicit error" ie the interval range).
Anyway, googling "ode solver interval arithmetic" or just "interval ode" turns up a load of interesting new and relevant stuff (VNODE and its references in particular).
If you have a stiff system, you will be using some form of implicit method in which case the derivatives are only used within the Newton iteration. Using an approximate Jacobian will cost you strict quadratic convergence on the Newton iterations, but that is often acceptable. Alternatively (mostly if the system is large) you can use a Jacobian-free Newton-Krylov method to solve the stages, in which case your approximate Jacobian becomes merely a preconditioner and you retain quadratic convergence in the Newton iteration.
Have you looked into using odeset? It allows you to set options for an ODE solver, then you pass the options structure as the fourth argument to whichever solver you call. The error control properties (RelTol, AbsTol, NormControl) may be of most interest to you. Not sure if this is exactly the sort of help you need, but it's the best suggestion I could come up with, having last used the MATLAB ODE functions years ago.
In addition: For the user-defined derivative function, could you just hard-code tolerances into the computation of the derivatives, or do you really need error limits to be passed from the solver?
Not sure I'm contributing much, but in the pharma modeling world, we use LSODE, DVERK, and DGPADM. DVERK is a nice fast simple order 5/6 Runge-Kutta solver. DGPADM is a good matrix-exponent solver. If your ODEs are linear, matrix exponent is best by far. But your problem is a little different.
BTW, the T argument is only in there for generality. I've never seen an actual system that depended on T.
You may be breaking into new theoretical territory. Good luck!
Added: If you're doing orbital simulations, seems to me I heard of special methods used for that, based on conic-section curves.
Check into a finite element method with linear basis functions and midpoint quadrature. Solving the following ODE requires only one evaluation each of f(x), k(x), and b(x) per element:
-k(x)u''(x) + b(x)u'(x) = f(x)
The answer will have pointwise error proportional to the error in your evaluations.
If you need smoother results, you can use quadratic basis functions with 2 evaluation of each of the above functions per element.