Why doesn't the less than operator work inside a for loop for decimals

Im trying to get the following code to work. but every time the value of x goes below 0.6 even though it an if condition is set to prevent it..can someone help
x=0.8;
for n=1:10
if (x>0.6)
x=x-0.1;
end
x
end

 採用された回答

James Tursa
James Tursa 2018 年 7 月 18 日
編集済み: James Tursa 2018 年 7 月 18 日
Floating point arithmetic effects. See this link for starters:
For your specific example,
>> x = 0.8
x =
0.8000
>> num2strexact(x)
ans =
0.8000000000000000444089209850062616169452667236328125
>> x = x - 0.1
x =
0.7000
>> num2strexact(x)
ans =
0.70000000000000006661338147750939242541790008544921875
>> x = x - 0.1
x =
0.6000
>> num2strexact(x)
ans =
0.600000000000000088817841970012523233890533447265625
>> num2strexact(0.6)
ans =
0.59999999999999997779553950749686919152736663818359375
>> x > 0.6
ans =
1
So, the successive subtractions of 0.1 don't get you exactly to the value you were expecting. The decimal fractions you are using can't even be represented exactly in IEEE double arithmetic anyway. You need to use different logic in your looping. E.g.,
y = 8; % 8 can be represented exactly in IEEE double
for n=1:10
if( y > 6 )
y = y - 1; % This subtraction will be done exactly in IEEE double
end
x = y / 10; % Now calculate the x value to use downstream
:
end

1 件のコメント

Shirosh Peiris
Shirosh Peiris 2018 年 7 月 19 日
Hi James
Thanks a lot for your answer..it makes sense now.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Community Treasure Hunt

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

Start Hunting!

Translated by