in Development, WTF

Floating point calculations or why 0.1 + 0.2 != 0.3

No matter what common programming language you use, the term 0.1 + 0.2 != 0.3 will evaluate to true. Go, try it out!

I stumbled over this problem when using coffeescripts for-loop to generate a range around a specific value:

range = (center) ->
  start_value = center - 0.1
  stop_value = center + 0.1
    
  stepping = 0.05
    
  num for num in [start_value..stop_value] by stepping

range(0.5)

A quick calculation in your head results in 0.4, 0.45, 0.5, 0.55 and 0.6. And it is mathematically correct. But not in the binary world we work in. There is a wikipedia article explaining this issue in detail, so I will float 😉 on the surface of the problem.

The solution is to remove the faulty floating point calculations:

integer_range = (center) ->
  factor = 100
  center *= factor
  start_value = center - 0.1 * factor
  stop_value = center + 0.1 * factor
    
  stepping = 0.05 * factor
    
  num/factor for num in [start_value..stop_value] by stepping

integer_range(0.5)

Moving the numbers to integer solves this problem. A jsfiddle containing this code can be found here.

So keep those floating points in mind!