How does MATLAB compare numbers?

I am using a while loop in my code shown below. Sometimes the program is entering the while loop even if a=b. I am inputting value b and the value of a is updated from the code show below. This is happening when let's say b=2 and a=2.0000. MATLAB is not correctly taking a=b.
Do I need to change significant digits?
while (a<b)
integral = integral+(h/2)*(f(a)+f(a+h));
a=a+h;
end

回答 (1 件)

Star Strider
Star Strider 2017 年 2 月 1 日

0 投票

‘Do I need to change significant digits?
You may need to understand how floating-point approximation works. See Why is 0.3 - 0.2 - 0.1 (or similar) not equal to zero? for a thorough discussion.
Rounding to a specific number of decimal places could help, but that itself is the result of a floating-point calculation and is not certain to produce the result you may want. It may be better to allow for a tolerance in your comparisons.
Also, please do not use ‘integral’ as a variable name, particularly if you have R2012a or later. It is the name of a function that does numerical integration. This is called ‘overshadowing’ of the built-in function and is best avoided.

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2017 年 2 月 1 日

回答済み:

2017 年 2 月 1 日

Community Treasure Hunt

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

Start Hunting!

Translated by