Ruby/Number/Float Extension

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Add absolute_approx to float class

class Float
  def absolute_approx(other, epsilon=Float::EPSILON)
    puts((other-self).abs)
    return (other-self).abs <= epsilon
  end
end
puts (1.8 + 0.1).absolute_approx(1.9)               # => true
puts 10e10.absolute_approx(10e10+1e-5)              # => false
puts 98.6.absolute_approx(98.66)
puts 98.6.absolute_approx(98.66, 0.001)



Add approx method to Float number

class Float
  def approx(other, relative_epsilon=Float::EPSILON, epsilon=Float::EPSILON)
    difference = other - self
    return true if difference.abs <= epsilon
    relative_error = (difference / (self > other ? self : other)).abs
    return relative_error <= relative_epsilon
  end
end
100.2.approx(100.1 + 0.1)               # => true
10e10.approx(10e10+1e-5)                # => true
100.0.approx(100+1e-5)                  # => false



Compare two floats for a certain precision

class Float
  EPSILON =1e-6 #0.000001
  def ==(x)
    (self-x).abs < EPSILON
  end
  def equals?(x,tolerance=EPSILON)
    (self-x).abs < tolerance
  end
end
x = 1000001.0/0.003
y = 0.003*x
if y == 1.0 # Using the new ==
  puts "yes" # Now we output "yes"
else
  puts "no"
end
flag1 = (3.1416).equals?Math::PI          # false
flag2 = (3.1416).equals?(Math::PI,0.001)  # true