필터 지우기
필터 지우기

Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

Why do I get false results when using equal relational operation for the logical operation?

조회 수: 1 (최근 30일)
I would like to get true when I use equal rational operation in a code including if condition. But I got false for the equal rational operation like as the below example. For example:
a = 0.2;
b = zeros(3,1);
if 12*a == 2.4
b(1) = 1;
end
if 14*a == 2.8
b(2) = 2;
end
if 17*a == 3.4
b(3) = 3;
end
>> b b = 0 0 0

답변 (2개)

Anish
Anish 2011년 1월 18일
If you look carefully at the definition of fundamental arithmetic operations like addition and multiplication, you soon encounter the mathematical abstraction known as the real numbers. But actual computation with real numbers is not very practical because it involves limits and infinities. So you need to avoid to using the result of multiplying floating points for the equal (==) operation because the result of multiplying floating points make the round off error.
Here is the link for the reference of floating points including IEEE Standard unifies arithmetic model:
As workarounds for this issue, use the integer for the variable 'a=2' instead of using floating points 'a=0.2' or rewrite your code like as below:
if (abs(a*12 - 2.4) < eps*10)

Walter Roberson
Walter Roberson 2011년 1월 20일
See also FAQ #6.1

이 질문은 마감되었습니다.

제품

Community Treasure Hunt

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

Start Hunting!

Translated by