pythonmathexpressionoperations

Why does Python evaluate this expression incorrectly?


I've been experimenting with the mathematical abilities of Python and I came upon some interesting behavior. It's related to the following expression:

(4+4)+3/4/5*35-(3*(5+7))-6+434+5+5+5

>>> 415

However, if you evaluate the expression with the standard order of operations in mind, the answer should be 420.25. I've also double checked with WolframAlpha, which gives an answer of 420.25. Why is Python giving a different answer? Does it have something to do with how it evaluates such expressions? Is there some convention that its following? Any info would be greatly appreciated, thanks!


Solution

  • You want to use floating point division. Changing it to this works:

    (4+4)+3.0/4/5*35-(3*(5+7))-6+434+5+5+5
    

    Some examples of integer division vs. floating point division:

    Python 2.7.2+ (default, Oct  4 2011, 20:06:09) 
    >>> 3/4
    0
    >>> 3.0/4
    0.75
    >>> 3.0/4.0
    0.75
    

    A float divided by an integer is a floating-point operation. Python 3 has changed this so that floating-point division is the default:

    Python 3.2.2 (default, Sep  5 2011, 21:17:14) 
    >>> 3/4
    0.75