This question already has answers here:
Why does Python return 0 for simple division calculation?
(6 answers)
What is the difference between '/' and '//' when used for division?
(16 answers)
Closed 4 years ago.
I have a line of Python code that doesn't work the way it should (at least to the best of my knowledge). Following is the code line:
print 'progress: {}%'.format((i/len(e_numbers))*100)
The value of i starts from 0 and goes up to length of e_numbers which is a list, while the length of e_numbers is around 17000. But the code always prints Progress: 0%.
Any idea why?
In Python 2, using / to divide two integers performs integer division by default, rounding the result down to the nearest integer value. Thus, as long as i is between 0 and len(e_numbers), i/len(e_numbers) is going to be 0. There are two possible solutions:
Cast one or both operands to a float before dividing, e.g., float(i)/len(e_numbers)
Put from __future__ import division at the top of your file so that / always produces a float.
Related
This question already has answers here:
Why does integer division yield a float instead of another integer?
(4 answers)
Closed 12 months ago.
First of all, sorry if this has been already answered, I have been searching for a while and did not find anything.
In short, I'm trying to create a programe to automate some tasks I have. In one, I have a loop on days, between a start date and an end date. For each iteration, I'm trying to get the lag in months between the current date and the start date. So I tried to use the euclidean division, which seemed appropriate.
Bottom line is, it works for almost all dates except a few, for instance:
import datetime as dt
start=dt.date(2022, 7, 1)
end=dt.date(2023, 7, 1)
average_days=365/12
lag1=(end-start).days/average_days
lag2=(end-start).days//average_days
For these dates in particular, lag1 gives me 12 while lag2 gives me 11. Where does this difference come from exactly, and how can I work around this issue to continue using the euclidean division ?
Thank you
This is answered here:
Dividing a Number by a Decimal Using the Integer Division Operator
In short, 365/12 is a float and is not exact after a certain number of digits. And could be a tiny bit larger than what you would expect. So when you divide 365 by this number it will be 11.99999... And // is floor division which truncates the decimals, resulting in 11.
This question already has answers here:
How do I do exponentiation in python? [duplicate]
(3 answers)
Closed 2 years ago.
I am new to programming and just started a course and stuck on a demo section where I have to take a math calculation and program it in Python. When I program it do you follow BEDMAS order of figuring out or is there a logical order. The syntax is correct but I keep being told it is not right
See the equation below to be programmed into python. What are the rules for telling Python to calculate something correctly where 5 is the exponent
Use Python to calculate (((1+2)∗3)/4)5
Exponentiation in Python is done with the ** operator.
For instance:
2**8
is 256.
In Python to calculate exponent you use ** operator.
Similar to multiplication but double asterisk.
(((1+2)∗3)/4)**5
This will give you 32.
That is because you are using values which are all integers, so 9 / 4 will be 2, not 2.25.
Python has operator precedence that follows algebraic rules.
This question already has answers here:
How do order of operations go on Python?
(5 answers)
Closed 2 years ago.
I tried to calculate the output of this problem in python: 4+6/2 and it was 7 then i reversed them as 6+4/2 and answer was 8. now whats the difference, and why this occurs? what is divided first?
Python uses PEMDAS, as do most languages. Division comes before addition, so it would be calculated as 4+(6/2)=4+3=7, and 6+(4/2)=8. This can be confirmed with any calculator.
PEMDAS is the standard order of operations:
P- Parentheses first
E- Exponents second
M/D- Multiplication or Division third (If there are multiple
multiplication or division signs in a row, then operate first to last)
A/S- Addition or Subtraction fourth (If there are multiple addition or
subtraction signs in a row, then operate first to last)
This question already has answers here:
Why does the division get rounded to an integer? [duplicate]
(13 answers)
Closed 4 years ago.
I'm solving some coding challenges on CoderByte and unfortunately they provide Python2. One thing I noticed is that the round() function is giving different outputs on python3 and python2. When i write this on python 2:
print int(round(100/60))
I get output of 1 (please explain why)
But on python 3 the same command gives 2 which is correct.
In python 2 the divide operator on integers returns integer, so 100/60==1. This unintuitive C-like behaviour was changed in python 3.
To make this code work properly in python 2 you should convert one of the integers to float: print int(round(100/60.)), that . means 60.0.
The problem is not the rounding, but the interpretation of /.
In python 2 if dividing 2 integers with / you get an integer not a float.
In python 3 you get a float if you use / - the "pure" integer division is done by using //.
Python 2:
print(100/60) # ==> 1
print(100/60.0) # ==> 1.6666666666...
Python 3:
print (100/60) # ==> 1.6666
print (100//60) # ==> 1
They both get rounded accordingly, but if you input a 1 into round, it will result in 1.
You can read more about the reason for the changed behaviour here: PEP 238
The current division (/) operator has an ambiguous meaning for numerical arguments: it returns the floor of the mathematical result of division if the arguments are ints or longs, but it returns a reasonable approximation of the division result if the arguments are floats or complex. This makes expressions expecting float or complex results error-prone when integers are not expected but possible as inputs.
We propose to fix this by introducing different operators for different operations: x/y to return a reasonable approximation of the mathematical result of the division ("true division"), x//y to return the floor ("floor division"). We call the current, mixed meaning of x/y "classic division".
This question already has answers here:
Integer division in Python 2 and Python 3
(4 answers)
Closed 5 years ago.
I am creating a game with coinflips. When all 100 coins are finished flipping I would like to calculate the percentage. The code provided below however, will either display "hp" or "tp" as 100 even though its obviously not 100%.
import random
flips=100
heads=0
tails=0
while flips!=0:
coinflip=random.randint(0,1)
if coinflip==0:
heads+=1
elif coinflip==1:
tails+=1
flips-=1
print "Heads - "+str(heads)
print "Tails - "+str(tails)
print "-----------"
hp=float((tails/heads)*100)
tp=float((heads/tails)*100)
I might be the way python processes things? or maybe I'm just stupid and cant do math.
Division in python2 is by default not floating point.
At the beginning of your code add an import
from __future__ import division
This adopts Python3's behavior
Previous Answer