0

I need a workaround for this issue. An explanation of why this is ONLY happening to one number would also be very helpful as I'd like to avoid this in the future. I've set the format long option to show what is happening.

I start by creating a vector. Just like this:

>> vec = [0, 2.4, 2.8, 5.2, 5.6]

It returns, as expected, this:

vec = 
0   2.400000000000000   2.800000000000000   5.200000000000000   5.600000000000000

Now, I want to add 0.4 to all of these:

>> vec + 0.4

But, here is my output:

ans =
0.400000000000000   2.800000000000000   3.200000000000000   5.600000000000001   6.000000000000000

Notice the rounding error on 5.6. It shouldn't have that 1. I tried using vec + round(0.4,1) but that also does not work.

Why does this only happen to 5.6? How can I avoid this? If it is unavoidable, how can I work around it?

EDIT: Also, in case this is useful.

MATLAB Version: 8.6.0.267246 (R2015b) Operating System: Microsoft Windows 7 Enterprise Version 6.1 (Build 7601: Service Pack 1) Java Version: Java 1.7.0_60-b19 with Oracle Corporation Java HotSpot(TM) 64-Bit Server VM mixed mode

toshiomagic
  • 1,335
  • 1
  • 12
  • 39
  • 2
    http://floating-point-gui.de/ – Oliver Charlesworth Mar 03 '16 at 21:53
  • What exactly is "working around it" supposed to mean? This is how numbers are stored in computer memory. – sco1 Mar 03 '16 at 21:53
  • @excaza - Sure, so how do you work around the fact that you can't store 5.6 exactly? – Oliver Charlesworth Mar 03 '16 at 21:54
  • I know where rounding errors come from. I just don't expect software like Matlab to have this issue. This breaks a lot of very simple code. A specific workaround in Matlab would be helpful. Oliver I'll look into that website you posted. – toshiomagic Mar 03 '16 at 21:59
  • The reason I need a work around is because I store `vec` and `vec4 = vec + 0.4` as two separate vectors. Then, I compare them with `vec==vec4`. I expect to get a logical array that tells me where numbers are equivalent so I can remove them. But this error means that the entire rest of my code cannot work unless I can find a workaround. – toshiomagic Mar 03 '16 at 22:02
  • 4
    You should basically never test for exact equality with respect to floating point values. Always test for a difference to some tolerance. E.g., `abs(vec1-vec4)<1e-8` instead of `vec1==vec4` – transversality condition Mar 03 '16 at 22:05
  • 2
    The moral of this story is you **don't** compare for exact equality. You use a tolerance. That's the crux of floating-point arithmetic. See the duplicate for more details. – rayryeng Mar 03 '16 at 22:09
  • @toshiomagic *all* software has this problem – sco1 Mar 03 '16 at 22:54

0 Answers0