user3196635
user3196635

Reputation: 21

Why does dividing by 1.8 not work, but multiplying by (5.0/9) does work?

I'm testing a simple program that converts Fahrenheit to Celsius, using Ruby.

This code returns 36.999999999 in terminal.

def ftoc(far)
    return (far-32)/1.8
end

ftoc(98.6)

This code returns 37.

def ftoc(far)
    return (far-32)*(5.0/9)
end

ftoc(98.6)

Can anyone tell me why? Thanks!!

Upvotes: 1

Views: 89

Answers (1)

David Grayson
David Grayson

Reputation: 87406

The type of numbers you are using are called floating point numbers.

In general, any floating point arithmetic operation will introduce rounding errors. You cannot expect two floating-point results to be exactly equal if they were computed in different ways; you must have some tolerance for small errors.

Upvotes: 4

Related Questions