Forum: Ruby on Rails Am I retarded?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
328f0bb678423fcea01ebe3b0edc74e6?d=identicon&s=25 Ben Johnson (benjohnson)
on 2007-01-04 19:36
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?

Thanks for your help.
F5c118aaeb5bb7162db613a37e595be8?d=identicon&s=25 Mick Sharpe (micksharpe)
on 2007-01-04 21:23
Ben Johnson 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?
>
> Thanks for your help.

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. :]
94cc3e46cfc5bc361e409e2e884ecfa4?d=identicon&s=25 Drew Olson (Guest)
on 2007-01-04 21:32
Ben Johnson wrote:
> What's the deal?
>
> Thanks for your help.

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
83ca41657a99b65d99889abe712ba5e2?d=identicon&s=25 Jason Roelofs (Guest)
on 2007-01-06 19:30
(Received via mailing list)
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
This topic is locked and can not be replied to.