Sometimes you will do a calculation where the answer looks like ‘0′ or ‘1′ or some other number like that. The natural thing to do is to do a test like this:
if (answer == 1)
Do something
end
However, if the calculation was done in double precision, answer might actually be 1.000000001 or something like that. This video discusses a strategy for overcoming this:
Your solution will work if the integer is known, as it is in this case (1). However Doug’s solution is more general in that it can be applied to determine if an integer is present when the integer may be unknown. As in:
abs(round(N) - N)<tol
Where N can be an array of possible integers which resulted from a previous calculation. This will be true when integers are found in N and false where not.
@paramesh - I don’t like the ROUND solution at all. That would return true for 1.4 and .6! As matt fig points out, you need to set a tolerance bound on your comparison.
That’s true Seth, but you can use a type of trick to make it more precise, like [i]round(100*w)/100[/i] or even [i]round(1000*w)/1000[/i].
Anyway, great solution Doug… I was having a little bit of problem with that, when I was making comparisons to find the intersection points of plots, and this method can be better than mine.
Leave a Reply
About
Doug Hull is a proud MathWorker who is on a mission to help you with MATLAB.
Hi Doug,
Nice point. But instead, won’t the function “round” work? Say, “if round(answer) == 1″.
paramesh,
Your solution will work if the integer is known, as it is in this case (1). However Doug’s solution is more general in that it can be applied to determine if an integer is present when the integer may be unknown. As in:
abs(round(N) - N)<tol
Where N can be an array of possible integers which resulted from a previous calculation. This will be true when integers are found in N and false where not.
@paramesh - I don’t like the ROUND solution at all. That would return true for 1.4 and .6! As matt fig points out, you need to set a tolerance bound on your comparison.
That’s true Seth, but you can use a type of trick to make it more precise, like [i]round(100*w)/100[/i] or even [i]round(1000*w)/1000[/i].
Anyway, great solution Doug… I was having a little bit of problem with that, when I was making comparisons to find the intersection points of plots, and this method can be better than mine.