Re:Calculating the mean of a list of numbers (2016)
by aboutruby on Saturday March 23, 2019 @01:04PM
(#19471250)
In ruby you need to use bigdecimal:
precision = Float::DIG + 1
require 'bigdecimal'
a = BigDecimal(8.98846567431158e+307, precision)
b = BigDecimal(8.988465674311579e+307, precision)
mean = (a + b) / 2
puts "Works" if mean > [a, b].min && mean < [a, b].max
=> Works
(edit: I used 0 first and it works fine but converts to precision 15 instead of 16 (which is the maximum on my computer) for some reason, I may file a bug for this)
Works for small floats too:
smalls = [1.390671161567e-309, 1.390671161567e-309, 1.390671161567e-309].map { BigDecimal(@1, precision) }
mean = smalls.sum / smalls.size
puts "Works" if mean >= smalls.min && mean <= smalls.max
=> Works
One could also use BigDecimal("8.98846567431158e+307") but seems like the numbers are coming as floats.
Works for small floats too:
One could also use BigDecimal("8.98846567431158e+307") but seems like the numbers are coming as floats.