How does MATLAB compare numbers?
Show older comments
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
Answers (1)
Star Strider
on 1 Feb 2017
0 votes
‘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.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!