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
Related examples in the same category