MATLAB precision and output question

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

KSSV
KSSV 2017년 5월 18일
10^-17 is zero only...how it matters? Why you are bothered?
Stephen23
Stephen23 2017년 5월 18일
"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

댓글을 달려면 로그인하십시오.

답변 (1개)

Jan
Jan 2017년 5월 18일
편집: Jan 2017년 5월 18일

0 개 추천

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

Lee Lee
Lee Lee 2017년 5월 18일
OK! May I ask how to increase the precision of MATLAB so that it will not omit very small value such as 10^-17 to zero ? Thanks.
Stephen23
Stephen23 2017년 5월 18일
편집: Stephen23 2017년 5월 18일
@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.

댓글을 달려면 로그인하십시오.

카테고리

태그

질문:

2017년 5월 18일

편집:

2017년 5월 18일

Community Treasure Hunt

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

Start Hunting!

Translated by