where is the error in this code?

clc,clear,close
v=[1.8 1.8 1.8 1.6];
a=1;b=0.0;
for j=1:9
z=a+b;
if z==1.8
disp('ok');
end
b=b+0.1;
end

回答 (2 件)

Vilém Frynta
Vilém Frynta 2023 年 4 月 22 日
編集済み: Vilém Frynta 2023 年 4 月 22 日

0 投票

In computer programming, when dealing with floating-point numbers, there can be slight differences in how these numbers are represented due to the finite number of bits used. As a result, when comparing such numbers using the "==" operator, unexpected results may occur due to these small errors in their representation.
Someone correct me if I'm wrong.
clc,clear,close
v=[1.8 1.8 1.8 1.6];
a=1;
b=0.0;
for j=1:9
z=a+b;
if z >= 1.799999999 && z <= 1.800000001
disp('ok');
end
b=b+0.1;
end
ok

5 件のコメント

Dyuman Joshi
Dyuman Joshi 2023 年 4 月 22 日
A better syntax would be
if abs(z-1.8)<tolerance
Where you can set tolerance according to the requirement.
Herman Khalid
Herman Khalid 2023 年 4 月 22 日
Thank you for your answers, but I tested from 0.0 to 5.0, just 1.8 had this issue?
Herman Khalid
Herman Khalid 2023 年 4 月 22 日
try to test with 1.6 or any other number you will get correct result
Vilém Frynta
Vilém Frynta 2023 年 4 月 22 日
@Dyuman Joshi thanks for your addition. i just tried to quickly show what i had on my mind.
@Herman Khalid it's possible. i do not have any deeper understanding this topic, but perhaps you could say that it's 'random'.
also, if you found my answer helpful, i'd be glad if you could accept it.
Dyuman Joshi
Dyuman Joshi 2023 年 4 月 22 日
Some floating point numbers can not be represented exactly in binary form.
You can see below what the values are stored as -
v = [1 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9];
vs = sprintf('%20.18f\n',v)
vs =
'1.000000000000000000 1.100000000000000089 1.199999999999999956 1.300000000000000044 1.399999999999999911 1.500000000000000000 1.600000000000000089 1.699999999999999956 1.800000000000000044 1.899999999999999911 '
Now compare that to the values of z -
a=1;b=0.0;
format long
for j=1:10
z=a+b;
zvalue=sprintf('%20.18f',z)
if z==1.8
disp('ok');
end
b=b+0.1;
end
zvalue = '1.000000000000000000'
zvalue = '1.100000000000000089'
zvalue = '1.199999999999999956'
zvalue = '1.300000000000000044'
zvalue = '1.399999999999999911'
zvalue = '1.500000000000000000'
zvalue = '1.600000000000000089'
zvalue = '1.699999999999999956'
zvalue = '1.799999999999999822'
zvalue = '1.899999999999999911'
Notice where the values differ?
So, while dealing with floating point numbers, always use a tolerance to compare.

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

カテゴリ

製品

リリース

R2023a

質問済み:

2023 年 4 月 22 日

回答済み:

2023 年 4 月 22 日

Community Treasure Hunt

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

Start Hunting!

Translated by