-3

When i try the code below in matlab, a and b is not equal shouldn't they be that?

a = 0.3
b = 0.1*3
a == b

Is this a bug or am I using the wrong operator to compare the number with?

user2864740
  • 60,010
  • 15
  • 145
  • 220
RollerBoy
  • 3
  • 1
  • 2
  • It's not a bug. It's because *relative precision floating point is not precise* (there is a very slight difference in bits between the result of 0.1 * 3 and 0.3 even if they are both *rounded* to "0.3" for display purposes). – user2864740 Oct 22 '13 at 19:10
  • when i try a < b i got True saying that b is larger than a. – RollerBoy Oct 22 '13 at 19:11
  • 9
    See http://stackoverflow.com/questions/686439/why-is-24-0000-not-equal-to-24-0000-in-matlab , http://stackoverflow.com/questions/6477178/about-floating-point-precision-why-the-iteration-numbers-are-not-equal?lq=1 (note use of fprintf to show more precision) , [What Every Computer Scientist Should Know About Floating-Point](http://www.validlab.com/goldberg/paper.pdf‎) , http://www.mathworks.com/matlabcentral/newsreader/view_thread/66553 – user2864740 Oct 22 '13 at 19:13
  • [This SO Q&A](http://stackoverflow.com/questions/13699596/is-this-a-matlab-bug-do-you-have-the-same-issue/13699714#13699714) is very close to your question, but with subtraction instead of multiplication. – chappjc Oct 22 '13 at 19:26

1 Answers1

1

Both are not equal, because floating point arithmetic has a certain precision. Check the difference (a-b) it should be really small.

For most programming languages, the answer is simply "deal with it, compare with a tolerance", but matlab has a symbolic toolbox. This also includes rational numbers and allows to eliminate this issue for some functions. Don't expect this to be a simple solution.

Daniel
  • 36,610
  • 3
  • 36
  • 69
  • Yes, and this question keeps coming up in some form on stackoverflow. Personally, I am fond of [the question on math.stackexchange.com simply titled "math equal does not work"](http://math.stackexchange.com/questions/434438/matlab-equal-does-not-work). The "right" operator with which to compare floating point numbers might be an "almost equal" test like `abs(a - b) < epsilon`. – chappjc Oct 22 '13 at 19:33