Question

I computed the following 2 values in python and got different results! It would be great if someone could reason it why it is happening like this.

(111 - (111 + 2*17)*3375)/(-14) gives 34947 as output.

(111 - (111 + 2*17)*3375)/(14)*-1 gives 34948 as output.

Both terms are mathematically equivalent.

Was it helpful?

Solution

This has to do with the rounding rules. Consider a simpler example:

>>> -3/(-2)
1

>>> -3/2*-1
2

1.5 is rounded down to 1, and -1.5 is rounded down to -2. Consistent, in a way.

Doc reference:

Plain or long integer division yields an integer of the same type; the result is that of mathematical division with the ‘floor’ function applied to the result.

If you want a floating point result in Python 2.x, you need either an explicit conversion (or just use float literals), or do from __future__ import division. In Python 3.x, division always produces a float (ref).

OTHER TIPS

You're doing integer math, which rounds the fractional result differently depending on whether it's negative or positive. Using floating point division:

>>> (111 - (111 + 2*17)*3375)/(14.)*(-1)
34947.42857142857
>>> (111 - (111 + 2*17)*3375)/(-14.)
34947.42857142857

It comes down to the way that python handles integer division.

If iether the numerator(top) or divisor(bottom) of your division is negative then python will round away from zero. A simple way to convince yourself of this is to compare two simpler fractions: 25/6 and 25/(-6). These will yield 4 and -5 respectively.

In order to get the same results you could us a float ie 14.0 to shift to floating point arithmatic.

If you are interested in more of the mathematics this seemed to be a pretty good article: http://python-history.blogspot.co.nz/2010/08/why-pythons-integer-division-floors.html

As mentioned earlier python division and rounding seems issue Here is how to fix it

In [10]: int((111 - (111 + 2*17)*3375)/(-14.0))
Out[10]: 34947

In [11]: int((111 - (111 + 2*17)*3375)/(14.0)*-1 )
Out[11]: 34947
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top