Why is Python evaluating this expression incorrectly?

I was experimenting with the mathematical capabilities of Python, and I came across some interesting behavior. This is due to the following expression:

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

However, if you evaluate an expression with a standard order of operations, the answer should be 420.25. I also double checked with WolframAlpha, which gives an answer of 420.25. Why does Python give a different answer? Does he have anything to do with how he evaluates such expressions? Is there any convention following it? Any information would be greatly appreciated, thanks!

+6
source share
6 answers

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

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

Some examples of integer division compared to 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 changed this so that the default floating point division:

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

Since Python 2 / uses integer division when both operators and operand are integers.

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

+7
source

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

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

he will give the expected answer.

+4
source

It depends on the version of Python you are running on:

 $ 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 

Prior to Python 3, the / operator performed integer division instead of floating point.

+4
source

This is an integer division. In your example, 3/4 is evaluated to 0. However, 3.0/4.0 is evaluated 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 has been changed in versions of Python 3 and later. If you want it to be floated by default, you can import this rule.

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

It is important to note that neither python nor WolframAlpha will give you the mathematically correct answer, since in mathematics we do multiplication before division, and in python * and / we have the same priority, so we will evaluate from 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 
+1
source

Source: https://habr.com/ru/post/908742/


All Articles