Settings

Theme

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

2 points by ajimix 6 years ago · 7 comments · 1 min read

Reader

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

ThrowawayR2 6 years ago

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.

  • ajimixOP 6 years ago

    thanks for the clear explanation. It's strange to me as a newbie in ruby that this can happen and I think that can lead to errors if you don't take that into account when doing calculations with numbers... Good to know

    • Dajve_Bloke 6 years ago

      NB - you get the same result in MS-SQL (and for exactly the same reason).

      Ruby behaves like SQL in that appending a decimal to the values results in non-integer maths being employed.

      MS-SQL itself is slightly out (I assume due to floating point inaccuracy)

      SELECT (289.0 / 30.0 * 30.0) - (149.0 / 30.0 * 30.0) 140.0000100

    • ThrowawayR2 6 years ago

      The distinction between integers and floating point variables is the same in most mainstream languages and is not specific to Ruby.

Dajve_Bloke 6 years ago

289/30 = 9 as it's truncating the non-integer part of the operation. So the calculation evaluates to 270 - 120 = 150

mtmail 6 years ago

It defaults to integer arithmetic. 5/3 will return 1. 5.to_f/3 will return 1.6666666666666667

oregontechninja 6 years ago

This is a stack overflow question buddy

Keyboard Shortcuts

j
Next item
k
Previous item
o / Enter
Open selected item
?
Show this help
Esc
Close modal / clear selection