3

I have a problem which I think is a bug. So I have created a for loop:

var multi=2;
 for (limit=0; limit < length; limit += 1.2) {
      multi++;
 }
 console.log(multi);

The output is correct for all range of values except for the instance where length=10.8 or any multiples thereof. The output shows as multi=12 which in fact it should be 11.

Can somebody tell me why is this happening?

Thanks!

John Hascall
  • 9,176
  • 6
  • 48
  • 72
gunbalde06
  • 79
  • 1
  • 8
  • 8
    welcome to the wonderful world of [floating point arithmetic](https://en.wikipedia.org/wiki/Floating-point_arithmetic): http://stackoverflow.com/questions/588004/is-floating-point-math-broken – Nina Scholz Mar 22 '17 at 07:57
  • 1
    Also named as IEEE754 pitfalls. In some domains it is simply forbidden to use float as an incrementable variable to avoid absorption/cancellation. – LoneWanderer Mar 22 '17 at 08:01
  • Try to compute `(float_max_value) - 0.001` – LoneWanderer Mar 22 '17 at 08:03
  • You can try something like this: [JSFiddle](https://jsfiddle.net/Lb1ua0ur/1/) to fix it. – Rajesh Mar 22 '17 at 08:24
  • Thank you Rajesh! I was actually trying to do something like this but had trouble with what syntax to use. Thank you very much! – gunbalde06 Mar 22 '17 at 14:17

2 Answers2

0
var multi=2;
 for (limit=0; limit < 10.8; limit += 1.2) {
      multi++;console.log(limit +"-"+multi);
 }
 console.log(multi);

output is

0-3

1.2-4

2.4-5

3.5999999999999996-6

4.8-7

6-8

7.2-9

8.4-10

9.6-11

10.799999999999999-12 // yes here it should be 10.8

So final multi will be 12 . 10.79 is less than 10.8 so multi will be increase

Ashutosh Jha
  • 15,451
  • 11
  • 52
  • 85
0

because multi values is 2

var length = 10.8
var multi  = 1;
 for(limit = 0; limit<length; limit+=1.2) {
      multi++;
 }

console.log(multi); // 11

you can change limit+=1.2 to limit+=1.3 for getting 11

var length = 10.8
var multi  = 2;
 for(limit = 0; limit<length; limit+=1.3) {
      multi++;
 }

console.log(multi); // 11
  • Its not about fixing loop. Question is **why `9.6 + 1.2` yields 10.79999** and not `10.8`. That is already answer in the link shared by Nina – Rajesh Mar 22 '17 at 08:33
  • because 9.6 + 1.2 = 10.799999999999999 –  Mar 22 '17 at 08:39
  • that should also be the result with any language that implements IEEE floating point –  Mar 22 '17 at 08:55