0

I am converting Celsius into Fahrenheit using the code below, however the exact result I require is slightly different from the one I am getting, simply because I put the float division within brackets. My question is, why is this the case?

def convertToCelsius(temp)
  celsius = (temp.to_f - 32) * 5.0 / 9.0  # => -29.444444444444443
  return celsius                          # => -29.444444444444443
end                                       # => :convertToCelsius

convertToCelsius(-21)  # => -29.444444444444443

(See below the slight difference in result).

def convertToCelsius(temp)
  celsius = (temp.to_f - 32) * (5.0 / 9.0)  # => -29.444444444444446
  return celsius                            # => -29.444444444444446
end                                         # => :convertToCelsius

convertToCelsius(-21)  # => -29.444444444444446
sdawes
  • 631
  • 1
  • 7
  • 15
  • @MichaelGaskill, no errors here, in the second instance author changed calculations order, so `-265.0 / 9.0` is not same as `-53.0 * (5.0 / 9.0)` for floats – Ilya May 19 '16 at 20:44
  • 1
    @Ilya The linked SO [ruby floating point errors](http://stackoverflow.com/questions/4055618/ruby-floating-point-errors) is unfortunately misnamed - there aren't actually *errors*, only slight calculation differences based on different *equivalent* expressions. Check out the article and the answers to see how alike they are to this question. – Michael Gaskill May 19 '16 at 20:49
  • 1
    Some reading on "significant digits" might also be useful. – mu is too short May 19 '16 at 20:57

0 Answers0