-1

So.. I'm trying to refactor a piece of code, namely:

v = [0.0, 0.10, 0.20, 0.30, 0.40, 0.50, 0.60, 0.70, 0.80, 0.90, 1.0]

By using the .step method. Tried this but it's giving me some odd decimals for some of the numbers. Trying to figure out why this is?

0.0.step(by: 0.1, to: 1.0).to_a

Gives me this result:

=> [0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6000000000000001, 0.7000000000000001, 0.8, 0.9, 1.0]

Ruby version: 2.3.0p0

How can I go about figuring out why this is happening? Each of those numbers returns a float.

virtuexru
  • 858
  • 1
  • 6
  • 16

1 Answers1

0

Floats are inexact. Calculations (like adding) are more exact using Rationals. If you must use floats, convert to Floats after the calculations.

p 0.step(1, 1/10r).map(&:to_f) 3 =>[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
steenslag
  • 79,051
  • 16
  • 138
  • 171