0

I am trying to figure out why a difference of 283 happens when I decide to multiply rather than divide.

Here is some Python code from my terminal. As you can see both variables are integers, but depending on whether I divide one to get to the other or multiply the other changes the value slightly.

>>> type(times), times
(<type 'int'>, 1512296383)
>>> type(payout), payout
(<type 'int'>, 5040987)
>>> [times / 300 - payout, times - payout * 300]
[0, 283]
>>> [times / 300, payout, times, payout * 300]
[5040987, 5040987, 1512296383, 1512296100]
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
rockets4all
  • 684
  • 3
  • 8
  • 32
  • What did you expect to happen? – President James K. Polk Dec 03 '17 at 21:48
  • 2
    @SilvioMayolo Not correct: `//` is explicit integer division and behaves the same in Python 2 and 3; `/` is integer or floating point division in Python 2, depending on the argument types, and is explicit floating point division in Python 3. – mkrieger1 Dec 03 '17 at 21:52
  • 1
    Possible duplicate of [Python division](https://stackoverflow.com/questions/2958684/python-division) – mkrieger1 Dec 03 '17 at 21:56
  • Also related: https://stackoverflow.com/questions/183853/in-python-2-what-is-the-difference-between-and-when-used-for-division, https://stackoverflow.com/questions/1267869/how-can-i-force-division-to-be-floating-point-division-keeps-rounding-down-to-0 – mkrieger1 Dec 03 '17 at 21:56

2 Answers2

1

You are performing integer division, which discards everything after the decimal point. Since times isn't divisible by 300, you'll get a truncated result. Here's a simpler way to see it:

>>> 1512296383 / 300 * 300
1512296100
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

Your issue is that in Python 2.x, integer division does not return an exact floating point result. Casting one value to a float shows that the division does not exactly equal 300:

>>> float(1512296383)/5040987
300.0000561397996

Therefore when you do 1512296383/5040987, you'll get the integer 300, which will introduce a small error.

S. G.
  • 63
  • 5
  • `1512296383.` or `5040987.`is enough. – keepAlive Dec 03 '17 at 21:49
  • @Kanak True, I did an explicit cast since I figured it'd be more helpful for the example in the question, since they'd need to do something like `float(times[0])`. – S. G. Dec 03 '17 at 21:52