Is there a bug in the if function

2 views (last 30 days)
tianyuan wang
tianyuan wang on 30 Jul 2020
Edited: Stephen23 on 30 Jul 2020
for example
if 0.0001575*1800<=5*0.0567
The theoretical result should be 1, but the output is 0

Answers (3)

Sriram Tadavarty
Sriram Tadavarty on 30 Jul 2020
HI Tianyuan,
The issue is not with the if condition, but the way the MATLAB deals with the floating point numbers. "Almost all operations in MATLAB are performed in double-precision arithmetic conforming to the IEEE standard 754"
If you evaluate the condition in command window, it provide value 0.
Here are few ways to avoid common problems using airthmetic floating point numbers, have a look here.
To solve this you can try round off for the condition and expect the valid condition.
Hope this helps.

Vladimir Sovkov
Vladimir Sovkov on 30 Jul 2020
This is not a bug in the if function but an artefact of the rounding of the matlab bit-wise arithmetics. To avoid this effect, several approaches can be used, e.g.,
if sym(0.0001575*1800)<=sym(5*0.0567)
although it would work slower than the purely numerical version.

Walter Roberson
Walter Roberson on 30 Jul 2020
> 0.0001575*1800-5*0.0567
ans =
> sym(0.0001575)*1800-5*sym(0.0567)
ans =
> sym(1575)/sym(10000000)*1800-5*sym(567)/sym(10000)
ans =
> sym(0.0001575) - sym(1575)/sym(10000000)
ans =
That one tells us that the approximation of 0.0001575 by the symbolic toolbox is not the same as 1575/10000000 .
> fprintf('%.999g\n', 0.0001575)
... because the closest binary double precision representation to 0.0001575 is a number which is slightly larger than an exact fraction.
> sym('0.0001575')*1800-5*sym('0.0567')
ans =
So if you use the symbolic toolbox carefully you can get the comparison to work out.
But the problem is not with "if": it has to do with the way that binary double precision numbers are represented. double() does not use decimal representation internally (IEEE has defined an equivalent decimal standard to the very common binary standard, but the only vendor that I know of that implements the decimal hardware, is IBM in their z90 series.)
This is a very common issue to have show up. When you compare two double precision numbers that have been calculated through different paths, you should always take into account precision limitations. For equality comparisons, use ismembertol() . Otherwise, instead of testing A <= B, test A <= B + tolerance

Community Treasure Hunt

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

Start Hunting!