Question

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!

Was it helpful?

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

OTHER TIPS

Because, in Python 2, / uses integer division when both the operator and operand are integers.

You can either change one to a float (as other answerers have suggested), or use from __future__ import division: http://www.python.org/dev/peps/pep-0238/

In Python 2.x the / operator is integer division. If you write

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

it will give the expected answer.

That depends on the version of Python you're running:

$ python3
Python 3.1.4 (default, Nov 12 2011, 12:16:31) 
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> (4+4)+3/4/5*35-(3*(5+7))-6+434+5+5+5
420.25

Before Python 3, the / operator performed integer division instead of floating-point.

It's integer division. In your example, 3/4 evaluates to 0. However, 3.0/4.0 evaluates to 0.75.

>>> (4+4)+3/4/5*35-(3*(5+7))-6+434+5+5+5
415
>>> (4+4)+3./4/5*35-(3*(5+7))-6+434+5+5+5
420.25

This behavior was changed in Python versions 3 and greater. If you want it to default to floating point division, you can import the rule.

>>> from __future__ import division
>>> (4+4)+3/4/5*35-(3*(5+7))-6+434+5+5+5
420.25

its important to notice that neither python or WolframAlpha will not give you the mathematically right answer since in math we do multiplication before division and in python * and / have the same precedence so will evaluate left to right.

3.0/4/5*35 # equal 5.25 in python
3.0/4/5*35 # equal 3.0/4/(5*35) or 0.004285714285714286 in math
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top