I have some code:
num1 = 1.001
num2 = 0.001
sum = num1 + num2
puts sum
I expected 1.002000
but I am getting 1.0019999999999998
. Why is this the case?
I have some code:
num1 = 1.001
num2 = 0.001
sum = num1 + num2
puts sum
I expected 1.002000
but I am getting 1.0019999999999998
. Why is this the case?
This is a commonly-found, fundamental problem with binary representation of fractional values, and is not Ruby-specific.
Because of the way that floating-point numbers are implemented as binary values, there are sometimes noticeable discrepancies between what you'd expect with "normal" decimal math and what actually results. Ruby's default representation of floating-point numbers is no exception--since it is based on the industry-standard double-precision (IEEE 754) format, it internally represents non-integers as binary values, and so its approximations don't quite line up with decimal values.
If you need to do decimal calculations in Ruby, consider using BigDecimal
(documentation):
require 'bigdecimal'
num1 = BigDecimal.new("1.001")
num2 = BigDecimal.new("0.001")
puts num1 + num2 #=> 0.1002E1
In a perfect world yes you expected that 1.002000, but you have an error due to rounding in floating point arithmetic operation, you can check on the web machine epsilon or just floating point. For example, you can calculate the relative error like that, and the error machine for the ruby language is 1e-15
f = 0.0
100.times { f += 0.1 }
p f #=> 9.99999999999998 # should be 10.0 in the ideal world.
p 10-f #=> 1.9539925233402755e-14 # the floating-point error.