Reputation: 21
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
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