MATLAB precision and output question
13 views (last 30 days)
Show older comments
I have the function
f= @(x) abs(abs(abs(abs(x)-0.9.*0.5)-0.9.*0.25)-0.9.*0.125)
If I enter f(0.1125), the actual answer should be 0, but MATLAB returns 1.38777878078145e-17
So I change function to
f= @(x)abs((1000*abs((1000*abs((1000*abs(x)-1000.*0.9.*0.5)/1000)-1000.*0.9.*0.25)/1000)-1000.*0.9.*0.125)/1000)
And f(0.1125)=0
But the second question is when I enter f(0.1125+10^-17), the answer should be 10^-17,but MATLAB answers 0
How can I solve this problem ?
2 Comments
Stephen23
on 18 May 2017
"the actual answer should be 0, but MATLAB returns 1.38777878078145e-17"
No, the output is correct. Because that is how floating-point arithmetic works. Small differences in the floating-point values means that you should not expect an output equivalent to some mathematical operation/s. Floating-point numbers have been explained a thousand times on this forum:
etc, etc, etc
Answers (1)
Jan
on 18 May 2017
Edited: Jan
on 18 May 2017
Welcome to the world of arithmetics with limited precision. Read the links posted by Stephen to see, that this topic has been discussed repeatedly and exhaustively.
See:
1e17 + 1 - 1e17
Here the order of terms matters, because internally numbers are stored with about 16 digits only. Such effects are well known and expected, because most decimal numbers do not have an exact representation in binary format (and vice versa). In consequence, this is not considered as a "problem", which can be "solved", but as something you have to cope with in numerics. Therefore this belongs to the first chapter of each book about numerics and is explained in the first lessons.
2 Comments
Stephen23
on 18 May 2017
Edited: Stephen23
on 18 May 2017
@Lee Lee: you will get exactly what you are looking for as soon as you tell us how to write 1/3 as a decimal using four digits of precision and without any loss of accuracy.
The point is, you need to understand floating point values. Repeatedly asking for impossible things does not help you to understand floating-point values. If you do not like how numeric calculations are, then consider using symbolic ones.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!