Very simple 'if' statement with == operator not working

조회 수: 18 (최근 30일)
Graham
Graham 2017년 12월 22일
댓글: Star Strider 2017년 12월 22일
I have some very basic logic that is not working. It's a simple 'if' statement with an '==' operator. Please help.
Program:
%simple_script.m
clear all
A = 0.40;
B = 0.20;
C = 0.60;
D = A + B;
if C == D
disp('It worked.')
else
disp('It did not work.')
end
Command Window:
>> simple_script
It did not work.
>>

채택된 답변

Star Strider
Star Strider 2017년 12월 22일
Welcome to the apparent inconsistencies of floating-point calculations. See the discussion in Why is 0.3 - 0.2 - 0.1 (or similar) not equal to zero? (link) for more informaiton.
Floating point approximations are similar in this regard to decimal 1/3 being approximated as 0.3333... Multiplying by 3 then gives 0.9999..., not 1.
  댓글 수: 2
Graham
Graham 2017년 12월 22일
Thanks!
Star Strider
Star Strider 2017년 12월 22일
My pleasure!
A further illustration:
Test = C - D
Test =
-1.110223024625157e-16

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

추가 답변 (1개)

Geoff Hayes
Geoff Hayes 2017년 12월 22일
Graham - you are incorrectly trying to use equality with floating point numbers. See the Compare Floating-Point Numbers section of determine equality for an example of what to do.

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by