Python 2 decimal division unexpected results [duplicate] - python

This question already has answers here:
How can I force division to be floating point? Division keeps rounding down to 0?
(11 answers)
Closed 6 years ago.
I am trying to do the calculation
Using the python decimal module with the following code:
from decimal import *
getcontext().prec = 9
sum = Decimal(0)
for i in range(1,11):
sum += Decimal(1/(i**4))
print sum
however, this outputs 1, not a very small fraction like I would expect. I can't find much information here https://docs.python.org/2/library/decimal.html about what is wrong with the code. My guess is sum is not being used as a Decimal in the loop, but I am unsure how to resolve that.

If you use Python 2.x, then in the expression: 1/(i**4), the integer devision is used, as result for i=1, it equals to 1 and for all other i>1, it gets 0.
Just add floating point to 1: 1./(i**4), this should fix the problem.
PS In Python 3.x, your code should work as expected, because operator / is defined on floating point numbers, while operator // is defined for integers.

First of all, don't use sum as a variable name, as it is a built-in.
And its sort of necessary to provide at least one float for arithmetic if you expect a float-type answer, here:
s = Decimal(0)
for i in range(1,11):
s += Decimal(1./(i**4)) # dividing 1. or 1.0 instead of just 1
print s
this gives:
1.08203658

Related

Terminal not printing python code on Mac [duplicate]

This question already has answers here:
How can I force division to be floating point? Division keeps rounding down to 0?
(11 answers)
Closed 5 years ago.
I made a small python file on my desktop for fun, and I'm frustrated to find that no values are being returned. Here is the code from the file:
def calc(x):
chance =1
for i in range(1,x+1):
chance *= ((365-i)/365)
return chance * 100
string = calc(23)
print string
And here is what I type into the terminal:
cd Desktop #where file is located
python py.py #py is the name of the file
And this is what it returns:
0
Since 365 and i are integers, you are performing integer division, which only returns the "whole" part of the result. Since 365-i is lesser than 365 dividing the two will result in 0, and continuously multiplying it by anything will still give 0.
You could use the 365.0 notation to use floating point division, which will eventually generate the result 46.1655742085:
chance = 1
for i in range(1,x+1):
chance *= ((365.0 - i) / 365.0)
# Floating point^-----------^
Well so on your first iteration your i = 1. 365-1 = 364. 364/365 = 0 because it is integer division in python. So the answer will always give you 0 unless you change it to allow for you to give a float.
Changing 365 to 365.0 will give you your answer
chance = chance * ((365-i)/365.0)
I just changed the 365 to 365.0 and I got
2.23071139399e-05
As my output
The result is correct in Python2.x. When a/b and a is less than b, result is 0.
Modify 365 to 365.0 it will cast the division result to float
chance *= ((365-i)/365.0)

Python small decimals automatically round to 0 [duplicate]

This question already has answers here:
How can I force division to be floating point? Division keeps rounding down to 0?
(11 answers)
Closed 6 years ago.
I have a simple problem:
print 1 / 100
returns
0
and
print float(1 / 100)
returns
0.0
Why does this happen? Shouldn't it return 0.01? Thank you for any help.
Simple solution!
print 1 / float(100)
Your problem is that by default in Python 2 the division operator will do integer division (rounding down to integer). By making one of the operands a float, Python will divide in the expected way. You were almost there with float(1 / 100), however all this accomplishes is doing the integer division of 1 by 100, which equals zero, then converting zero to a floating point number.
This is a recognized issue in Python 2, fixed in Python 3. If you get tired of writing x / float(y) all the time, you can do from __future__ import division to make the division operator behave as in Python 3.
You are doing integer division. What you've written is, for all intents and purposes:
float(int(1)/int(10))
For example:
assert float(10/3) == 3.0 # True
You need to have at least one of them implicitly or explicitly a float. All of these are valid:
float(1.0/100.0)
float(1.0/100)
float(1/100.0)
float(float(1)/float(100))
etc...
You are doing integer division, when expecting a decimal (float), you can assert an integer to be a float by placing a decimal at the end, i.e.
print 1 / 100.

Python exponential calculation on fraction [duplicate]

This question already has answers here:
Why does the division get rounded to an integer? [duplicate]
(13 answers)
Closed 6 years ago.
I'm trying to calculate 27^(1/3) = 3. But it turns out not as expected.
>>> 27 ** (1/3)
1
>>> 27 ** (1/3.)
3.0
Firstly, why the first calculation will result in 1, is it because 1/3 is casted to an int so it equals zero?
Secondly, what does the '.' means in Python in general, could I append a dot to any number in order to cast it from int to double?
Thanks.
Firstly, why the first calculation will result in 1, is it because 1/3
is casted to an int so it equals zero?
Yes, that's exactly it.
what does the '.' means in Python in general, could I append a dot to
any number in order to cast it from int to double?
The . is explicitly making the number a float as 1.0 would be opposed to just 1.
You experience integer division in python 2.
in python 2:
>>> 2/3
0
In python 3:
>>> 2/3
0.6666666
If you want the python3 behaviour in python2 you can do
from __future__ import division
as your first import.
For the integer division, use
>>> 2 // 3
0
Or you can use 2.0 / 3.0 to use floats.
In python 2.x, dividing integers defaults to floor division, so any non-integer quotient automatically rounds down to the nearest integer for example
>>> 1/3
0
>>> 5/2
2
So when you try to calculate 27 ** (1/3) you are just calculating 27 ** 0
There are numerous workarounds to the problem, the simplest way would be to just use floating points in the exponent - (1.0/3.0), or even just (1/3.0). However, if you were to be doing a lot of these calculations it might become annoying to constantly type out all the numbers in floating point form. In this case, you could use the future module to utilize Python 3.x division behavior, which always results in a floating point value:
>>> from __future__ import division
>>> 1/3
0.3333333333333333
This way the calculation will never default to floor division. And if at some point you want floor division in the same program, you can just use the // operator to get behavior similar to python 2.x integer division, like so:
>>> 1//3
0

How to tell python I need the decimals? [duplicate]

This question already has answers here:
How can I force division to be floating point? Division keeps rounding down to 0?
(11 answers)
Closed 8 years ago.
My program is to find the number of types, the number of tokens, and the type-to-token ratio. However, I don't know how to tell Python the answer to ttr is not an integer.
from nltk.corpus import inaugural
print inaugural.fileids()
tokens = inaugural.words("1789-Washington.txt")
numtokens = len(tokens)
print numtokens
types = sorted(set(tokens))
numtypes = len(types)
print numtypes
# This is the part I'm unsure about.
ttr = numtypes/numtokens
print ttr
If you are working in Python 3, the division operator / is performing floating point division by default:
>>> 3 / 2
1.5
>>> 4 / 2
2.0
since integer division is handled by the // operator.
In Python 2.x, if you want decimal accuracy in integer division, you can convert either the nominator or the denominator to float(), like this:
ttf = float(numtypes) / numtokens
Alternatively, as tobias_k points out, you can do
>>> from __future__ import division
>>> 3 / 2
1.5
to get Python3-esque division in Python 2.x

Python sum of digits error [duplicate]

This question already has answers here:
Why does integer division yield a float instead of another integer?
(4 answers)
Closed 8 years ago.
While solving Project Euler problems with Python (which I am a beginner at), I got this following error. The question is to find the sum of the digits of 2^1000. For that I wrote the following code :
sum=0
x=2**1000
while(x):
sum += x%10
print(sum) #Just to check whats happening
x /= 10
print("\n"*5)
print("Sum = ",sum)
For this, I get decimal added up somewhere in between.
Output :
6
10.0
10.0
12.0
16.0
....
1116.0
1122.0
1131.625 #Why does the decimal get added?
1138.59375
.....
1181.495136589947
1186.5812084526442
1188.089815638914
1195.240676357541
1195.9557624294036
1197.0272710365898
1197.1344218973084
1197.1451369833803
1197.1462084919874
.....
1197.1463275484991 #This number gets repeated a lot of times
1197.1463275484991
1197.1463275484991
Sum = 1197.1463275484991
Please explain what's going on and help.
Use integer division instead of floating point:
x //= 10
Do not know if you're looking for an alternative implementation, but this might be more straightforward if you don't want to risk crossing over into floating point land.
# Python 2.7
x = str(2**1000)
print sum([int(i) for i in x])

Categories

Resources