Round error using if statement. Two things don't equal each other

5 ビュー (過去 30 日間)
Derrick
Derrick 2011 年 10 月 4 日
Ok this is the problem I am having.
I have an M-File containing the following...
>> x = sin(pi/6)
>> y = cos(pi/6)
>> mytan = x/y;
>> if mytan == tan (pi/6)
disp('equal')
else
disp('not equal')
end
......
When I run it, I want to get 'equal' to display but I keep getting 'not equal'
I know x = .5000 or .500000000000000 using format long
and y = .8660 or .866025403784439 using format long.
now mytan = x/y
comes out to be .5774 or 0.577350269189626 using format long
and tan(pi/6) is .5774 or 0.577350269189626 using format long
I should be getting the "equal to display"
however I am not.
Im pretty sure this is due to round off error, so how should I change my if statement to get the equal message to display.
Thank You

採用された回答

Fangjun Jiang
Fangjun Jiang 2011 年 10 月 4 日
You are right about floating point rounding error. You can use eps
x = sin(pi/6)
y = cos(pi/6)
mytan = x/y;
if abs(mytan-tan(pi/6))<eps
disp('equal')
else
disp('not equal')
end
  3 件のコメント
Fangjun Jiang
Fangjun Jiang 2011 年 10 月 4 日
Yes, I did the re-formating. But I didn't pay particular attention. What type of problem did you have before?
Walter Roberson
Walter Roberson 2011 年 10 月 4 日
The original text with the >> lines was visually correct, and appeared to have 2 spaces at the beginning of every line, and showed up as formatted in the preview, but in the actual message display it showed up as if it was unformatted. I have encountered exactly the same situation once before and was hoping to preserve it so Mathworks could look at the binary of the file. Oh well. Next time.

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

その他の回答 (2 件)

Walter Roberson
Walter Roberson 2011 年 10 月 4 日
This is a known and unavoidable issue in any finite-precision computer, no matter what the base of arithmetic (decimal, binary, hex, whatever) that it uses. For more information, please read this FAQ

Derrick
Derrick 2011 年 10 月 4 日
Thank you Fangjun this worked for me. I was aware of eps and abs() i just didnt think to put them in like that. Thanks again.

カテゴリ

Help Center および File ExchangeJust for fun についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by