where is the error in this code?
조회 수: 4 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
답변 (2개)
Vilém Frynta
2023년 4월 22일
편집: Vilém Frynta
2023년 4월 22일
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
댓글 수: 5
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
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)
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
Notice where the values differ?
So, while dealing with floating point numbers, always use a tolerance to compare.
참고 항목
카테고리
Help Center 및 File Exchange에서 Install Products에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!