3

One of my friends wrote the following in Matlab and the outputs are little weird:

for p=0.01:0.01:0.1
100*p 
end

The following was the output:

1
2
3
4 
5
6.000000000000001
6.999999999999999
8
9
10

I'd like to know why there is a slight error? Does this mean that, the accuracy in the general case is also as poor as it is in this case?

EDIT:

We compared the numbers -- 7==6.999999999999999 and the output was 0. So, Matlab contradicts itself!

kan
  • 199
  • 9

3 Answers3

8

The problem is that 0.01 cannot be exactly represented in binary floating-point. Neither can 0.07.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
7

Looks like a floating point precision "issue": http://www.lahey.com/float.htm

Nick Veys
  • 23,458
  • 4
  • 47
  • 64
0

Try

x = ((0.07+1)*100) - 100

;-)

stevieb
  • 9,065
  • 3
  • 26
  • 36
rubens21
  • 743
  • 5
  • 13
  • got excited 7% (value is 0.07) maps back to correct UI presentation, that is 7. But then I tried this: `[0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.10].map(n => ((n + 1) * 100) - 100)` Output: `(10) [1, 2, 3, 4, 5, 6, 7, 8, 9.000000000000014, 10.000000000000014]` It's not working for other numbers, e.g., 9 and 10 – Michael Buen Mar 07 '18 at 05:03
  • That's true :/ and that's sad :'( We could try `Math.round((n + 1) * 100)`, but it will only work with 2 decimals precision. – rubens21 Apr 02 '18 at 16:54