Matlab returns different values with two equivalent functions

Let's say I have two functions:
f = @(x) (1.01.*exp(4.*x) - 4.62.*exp(3.*x) - 3.11.*exp(2.*x) + 12.2.*exp(x) - 1.99)
F = @(x) (((1.01.*exp(x) - 4.62).*exp(x)-3.11).*exp(x) + 12.2).*exp(x) - 1.99
These two functions are equivalent but when I want to execute with MATLAB it gives me different results with the same input. (for example with 0.925)
I would like to ask why cause this situation and which one has should I trust.
Thanks in advance!

2 Comments

>> f(0.925)
ans =
-24.2489
>> F(0.925)
ans =
-24.2489
Works as always
ans =
-24.2489252551835
ans =
-24.2489252551834
as you see it's not the same, and with 1.53 the difference is bigger

Sign in to comment.

 Accepted Answer

The difference between then in my computer with your example is -3.197442310920451e-14 (depending of your processor may be slightely different but still extremely low). This difference is negletible and can be regarded as numerical/approximation error between taking the exp of a number and multiplying two (to four, in your case) exp's. You can reproduce it easily with an easier example:
exp(3.245*2)-exp(3.245)*exp(3.245)
ans =
-1.136868377216160e-13
The results are then actually the same and you can trust both of them with the given accuracy, which should be enough for almost any application you may think.

6 Comments

So it means that you have not enough precision in MATLAB to produce the correct answer?
becaus for example when I execute f(1.53) and F(1.53) the difference is bigger than when I execute with 0.925. If I need to choose one of the two answers, which one should I choose? (I mean, which will produce less relative error percentual)
The problem is not with matlab, but rather with numerical computation itself. Even if you use variables with a higher precision (which, in matlab, I believe it only can be done with symbolic toolbox) you can never expect a result to be always "perfect". This truncation error is something that, unfortunately, anyone that uses computer calculations has to deal with. About your question of which one you should use, the answer is that it actually doesn't matter much. You always will have something like: Result = Realresult + numericalError. This numerical error is normally bounded and, even though some specific operations do provide less numerical errors, the difference between then is so minimal that only some very restricted application could take any advantage of it. If you really want a "black and white" answer, I would guess that the variant F can be slightely better since you have actually only one expoent computation and everything else is sum and multiplication, which should produce marginally less numerical errors.

Sign in to comment.

More Answers (0)

Products

Release

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!