# Fwd: Why this?

-------- Original Message --------
Subject: Why this?
Date: Sat, 13 Aug 2011 22:20:04 +0300
From: Николай [email protected]
To: [email protected]

Hallow, can anybody explain me that?
a = (102 + 52) #=> 125
b = Math.hypot(10, 5)**2 #=> 125.0
a == b #=>false
a.to_f == b #=> false
125.0 == 125 #=> true
125.0.to_f == 125 #=> true

On Sat, Aug 13, 2011 at 9:28 PM, Николай [email protected] wrote:

Hallow, can anybody explain me that?
a = (102 + 52) #=> 125
b = Math.hypot(10, 5)**2 #=> 125.0

a == b #=>false

http://ruby-doc.org/core/classes/Fixnum.html#M001090
They are not numerically equal.
b is not exactly 125.0, I’m not into details about ruby’s float
implementation, but the result simply isn’t 100% accurate. Try a.to_f ==
b.round

a.to_f == b #=> false

Same as above.

125.0 == 125 #=> true

http://www.ruby-doc.org/core/classes/Float.html#M000127

The 125.0 declaration is accurate, so numerical equality is true. As the
documentation says, this is not an eql? check (i.e. does not have to be
same
type).

125.0.to_f == 125 #=> true

Same as above.

For me, Math.hypot(10, 5)**2 is 125.00000000000001.

Float numbers are simply not accurate; you should perform “fuzzy”
comparisons - checking whether the difference between two floats is
smaller than a hard-coded really small number.

def fuzzy_eq a, b, eps = 1e-6
(a-b).abs < eps
end

– Matma R.

On Sat, Aug 13, 2011 at 12:28 PM, Николай [email protected] wrote:

Hallow, can anybody explain me that?
a = (102 + 52) #=> 125
b = Math.hypot(10, 5)**2 #=> 125.0
a == b #=>false
a.to_f == b #=> false
125.0 == 125 #=> true
125.0.to_f == 125 #=> true

The second result is the version of “inspect” bundled with your ruby

Ruby 1.9.2p180, via RubyInstaller, Win7 32-bit gives me:

irb(main):001:0> a=(102 + 52)
=> 125
irb(main):002:0> b=Math.hypot(10,5)**2
=> 125.00000000000001

IronRuby 1.1 gives me behavior that looks like what you see, but a
quick test shows that that “125.0” inspect value is skin deep:

irb(main):001:0> b=Math.hypot(10,5)**2
=> 125.0
irb(main):002:0> b<=>125.0
=> 1
irb(main):003:0> b==125.00000000000001
=> true

More generally, you are generally in deep trouble when you count on
floating point calculations producing exact results.

“Николай” [email protected] wrote in post #1016537:

Hallow, can anybody explain me that?
a = (102 + 52) #=> 125
b = Math.hypot(10, 5)**2 #=> 125.0
a == b #=>false

Try looking at (a-b)

For the long story see
http://docs.sun.com/source/806-3568/ncg_goldberg.html