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
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 Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!