-1

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

ajimix
  • 974
  • 7
  • 16
  • 5
    This isn't just Ruby, this is many programming languages where numbers without decimals are treated as integers. If you go through the math, but after each operation you remove the fractional part of the result, you'll get 150. – Thomas Jager Jun 28 '19 at 15:07

2 Answers2

3

That's because of the data type ruby uses for dividing, int is missing the fractional part of the result.

In Ruby :

289 / 30
=> 9
9 * 30
=> 270
289.0 / 30
=> 9.633333333333333

In Python (for example):

>>> 289 / 30
9.633333333333333
>>> 9.63333 * 30
288.9999
gogaz
  • 2,323
  • 2
  • 23
  • 31
2

This is integer math for you. 289/30 is equal to 9. By the way, same is in Python if you use // for integer division.

(289//30*30) - (149//30*30) = 150
Severin Pappadeux
  • 18,636
  • 3
  • 38
  • 64