from Hacker News

Ask HN: Why Ruby doesn’t know how to do maths?

by ajimix on 6/28/19, 2:51 PM with 7 comments

I'm not an expert in maths but the following operation gives a different result in ruby than in any other language or calculator I've tried:

Ruby: (289 / 30 * 30) - (149 / 30 * 30)

150

Rest of the world: (289 / 30 * 30) - (149 / 30 * 30)

140

An explanation is greatly appreciated

  • by ThrowawayR2 on 6/28/19, 3:13 PM

    289/30 is exactly 9 and 149/30 is exactly 4 because they are integer expressions. You need to specify the constants as floating point values if you want floating point behavior.

    Ruby does know how to do math and is doing precisely what you told it to.

  • by Dajve_Bloke on 6/28/19, 3:12 PM

    289/30 = 9 as it's truncating the non-integer part of the operation. So the calculation evaluates to 270 - 120 = 150
  • by mtmail on 6/28/19, 3:04 PM

    It defaults to integer arithmetic. 5/3 will return 1. 5.to_f/3 will return 1.6666666666666667
  • by oregontechninja on 6/28/19, 3:00 PM

    This is a stack overflow question buddy