# Am I retarded?

Doing a simple test here and I’m not really sure why this isn’t passing,
which makes me feel retarded. All that the amount method is doing is
taking 10% from the argument.

“#{@some_discount.amount(51)} == #{5.1}”
=> “5.1 == 5.1”

“#{@some_discount.amount(51).class.name} == #{(5.1).class.name}”
=> “Float == Float”

“#{@some_discount.amount(51) == 5.1}”
=> false

What’s the deal?

Ben J. wrote:

Doing a simple test here and I’m not really sure why this isn’t passing,
which makes me feel retarded. All that the amount method is doing is
taking 10% from the argument.

“#{@some_discount.amount(51)} == #{5.1}”
=> “5.1 == 5.1”

“#{@some_discount.amount(51).class.name} == #{(5.1).class.name}”
=> “Float == Float”

“#{@some_discount.amount(51) == 5.1}”
=> false

What’s the deal?

Floating point arithmetic cannot store some numbers exactly, and 5.1 is
one of them. Try executing “#{51/10 == 5.1}” and see what you get. :]

Ben J. wrote:

What’s the deal?

Ben -

I’m fairly sure that your problem here is the way ruby (and computers in
general) deal with floats. Floats are inherently imprecise and when you
perform mathematical operations with them, this imprecision will become
apparent.

irb(main):001:0> a = 5.1
=> 5.1
irb(main):002:0> b = 5.1
=> 5.1
irb(main):003:0> a == b
=> true
irb(main):004:0> x = 51 * 0.1
=> 5.1
irb(main):005:0> y = 5.1
=> 5.1
irb(main):006:0> x == y
=> false

Hope this helps.

-Drew

What you see is not what you get with floating point numbers. Have Ruby
print out 20+ decimal places and you’ll see that there is in-fact a
difference. When trying to compare floats, you need to use an epsilon
and
check that the two values are close enough to each other. e.g.

x = 5.1
y = 5.1
epsilon = 0.001

abs(x - y) < epsilon

Jason