# Question about accuracy of two different methods

2 views (last 30 days)
Devin on 14 Nov 2018
Commented: Devin on 15 Nov 2018
Greetings,
I have a question about accuracy. I have mathmatically equivalent method 1 and method 2. Practically, the final diffference beteween vol and vol1 is 8.8818e-15. In my program, this tiny difference can be amplified. But I still need to use method 1 form to get results as method 2.
%Method 1:
vol = 6
for i = 1:5000
vol = vol + 18.3 * 1e-3 * 0.1;
end
%Method 2:
vol1 = 6 + 18.3 * 1e-3 * 0.1 * 5000;
Does anyone can help me to explain why these two methods are different? And how can I get accurate results to avoid this tiny difference to be amplified?

Stephen on 14 Nov 2018
Method 1 has 5000 operations, each of which is bound to generate some error. Your machine epsilon may vary from mine, but mine is 2.2204 e-16 on a 64 bit installation of Matlab. (Type "eps" on your command line) Every Matlab operation is rounded to the nearest eps, so if you have 5000 operations, that is 5000 opportunities to accumulate error.
If you are extraordinarily unlucky, and each of those rounding errors went in the same direction, you might see as much as 5.5511e-13 in error accumulation. (max error = 5000*eps/2). So in reality, your accumulation of 8.88e-15 in error over 5000 operations is really not all that bad, as the errors seem to be distributed near the desired mean of zero. If your system is sensitive to that level of error, I would suggest you reconsider the reasons why you "must" use method one.
##### 3 CommentsShow 1 older commentHide 1 older comment
Stephen on 14 Nov 2018
Since you're using 64 bit, double precision variables in your code, there isn't much that you can do at this time. Some 64 bit applications use a "long double" variable type which would reduce machine epsilon to 2^-63 or 1e-19, but to my knowledge that is not offered by Matlab.
Devin on 15 Nov 2018
Thank you very much, I will discuss with my prof.

### Categories

Find more on Mathematics in Help Center and File Exchange

R2018a

### Community Treasure Hunt

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

Start Hunting!