If-statement do not respond

1 回表示 (過去 30 日間)
Sergey Dukman
Sergey Dukman 2015 年 7 月 13 日
コメント済み: Stephen23 2015 年 7 月 13 日
Hei! I am running the following function in matlab:
function trig(a,b)
format long
x=pi/9;
a=sin(4*x)
b=4*sin(x)*cos(x)-8*sin(x).^3*cos(x)
if (a==b)
disp('verified')
end
After calculating variables "a" and "b" I got the following values a=0.984807753012208 and b=0.984807753012208 (a=b). The problem is that my if-statment do not display "verified" after running a script. But if I type "if (a<b)" I do get 'verified'. Why is it so?
Thank you in advance.

採用された回答

Guillaume
Guillaume 2015 年 7 月 13 日
Check the difference between a and b:
>>b-a
ans = 1.110223024625157e-16
This is because floating point arithmetic is not exact on a computer. You accumulate small errors which means that, with floating point numbers that have been obtained by two different methods, you can never compare for equality with ==. Use a small enough tolerance for your case:
if abs(a-b) < 1e-14
disp('verified')
end
Also note that format only change the precision of the display. It does not affect in any way how the numbers are stored.
  1 件のコメント
Sergey Dukman
Sergey Dukman 2015 年 7 月 13 日
Thank you, Sir. I did not know about such "cobwebs" before. Your way to solve this problem looks suitable for me.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMAB Modeling Guidelines についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by