Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why ruby and python math calculation are different

Tags:

python

math

ruby

2 + 2 / - 7 * - 7 * 8 - 5 + 7 * -3

Python calculates this expression like this:

2+2/-7*-7*8-5+7*-3 == -8.0
# True

And Ruby like this:

2+2/-7*-7*8-5+7*-3 == 32
# => true

But the correct answer is -8.

Where am I wrong? Why the Ruby result is different from the Python one?

like image 888
Ivan Baksheev Avatar asked Nov 30 '22 08:11

Ivan Baksheev


1 Answers

This example is simpler:

In Ruby (and Python 2.x), 1/2 == 0. In Python 3.x, it's 0.5.

What's happening is that in Ruby and Python 2, / between two integers performs integer division (floors the true result).

The below will give you -8 in Ruby. Note the 2.0, making that a floating point value:

2+2.0/-7*-7*8-5+7*-3
like image 173
user94559 Avatar answered Dec 01 '22 22:12

user94559