Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 359
ThisIsNotAnId Avatar asked Feb 17 '12 20:02

ThisIsNotAnId


People also ask

How does Python evaluate expression?

You can use the built-in Python eval() to dynamically evaluate expressions from a string-based or compiled-code-based input. If you pass in a string to eval() , then the function parses it, compiles it to bytecode, and evaluates it as a Python expression.


2 Answers

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
like image 113
jterrace Avatar answered Oct 05 '22 08:10

jterrace


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/

like image 24
David Wolever Avatar answered Oct 05 '22 06:10

David Wolever