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.
Related
This question already has answers here:
Why does floating-point arithmetic not give exact results when adding decimal fractions?
(31 answers)
Closed 4 months ago.
a = [0.0021, 0.0087]
s = sum(a)
print(s)
Outcome: 0.010799999999999999
When executing the program above, the result is complex and eronated.
After performing multiple tests, including:
a = 0.0021
b = 0.0087
The result is the same. I tried different combinations of numbers and it seems that only these 2 have such an odd outcome.
I would say that this is floating point arithmetics error. Or I think there were some performance improvements done to math operations in Python which cause this, you can look more into it if you want by searching for PyNumber_Add and BINARY_ADD operation
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 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.
This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 5 years ago.
I have the code already figured out and have found a way to get around the problem that for k > 6 the largest denominator is very large. But when my code adds up for example
1/float(2) + 1/float(3) + 1/float(7) + 1/float(42)
python says that it is not equal to 1, but it should be. Why does python recognize other sums as being equal to 1 but not this one?
It is because you are asking for floating point arithmetic, and when the roundoff errors add up, you'll get wrong answers.
Use the https://docs.python.org/3/library/fractions.html module to get real fractions and roundoff issues should disappear for you.
You need to be extremely careful when hard-comparing any decimal values. Computer don't provide unlimited precision, thus it could be that your argument adds up to something like 0.99999998 instead of 1. Then the comparison might fail.
Thus you should always compare corresponding to an allowed difference of delta, like 1 - 0.99999998 < delta where delta = 0.0001 or something like that.
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