Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-zero arithmetic check in Python

This math equation...

(4195835 / 3145727) * 3145727 - 4195835

is supposed to equate to 0. According to the book Software Testing (2nd Ed),

If you get anything else, you have an old Intel Pentium CPU with a floating-point division buga software bug burned into a computer chip and reproduced over and over in the manufacturing process.

Using Python 2.7, I get -1050108 in command line.

Using Node I get 0, just as I would in the calculator

Any deeper explanation for this? This was originally brought up due to a bug in the video game Disney's Lion King, 1994. I thought I would test the equation on a few things.

like image 711
Shane Avatar asked Feb 12 '26 11:02

Shane


2 Answers

You did integer math and not floating point math.

>>> (4195835 / 3145727) * 3145727 - 4195835
-1050108
>>> (4195835. / 3145727.) * 3145727. - 4195835.
0.0

Note that you can get the behavior you want from integers using py3k or PEP238 division.

>>> from __future__ import division
>>> (4195835 / 3145727) * 3145727 - 4195835
0.0
like image 145
Brian Cain Avatar answered Feb 15 '26 01:02

Brian Cain


With integer math (which is what you're using), (4195835 / 3145727) will give you 1.33382... rounded down to the integer 1.

So you effectively end up with:

  (4195835 / 3145727) * 3145727 - 4195835
=          1          * 3145727 - 4195835
=                       3145727 - 4195835
=                           -1050108

which is why you get that negative number.

You can force it to use floating point just by making one of the values floating point:

>>> (4195835. / 3145727) * 3145727 - 4195835
0.0
like image 28
paxdiablo Avatar answered Feb 15 '26 02:02

paxdiablo