Python finding n as 101 instead of 100 [duplicate] - python

This question already has answers here:
Why does the division get rounded to an integer? [duplicate]
(13 answers)
Closed 6 years ago.
Python loops are finding n as 101 instead of 100, I am getting the average of 5050 as 50 instead of 50.50, What could be the problem? How should I go through it? Here is my function.
def sum_and_average(n):
total = 0
for i in range(1, n+1):
total += i
average = float(total/n)
print "the sum is %d and the average is %f" %(total, average)
sum_and_average(100)
It returns:
the sum is 5050 and the average is 50.000000

Do float(total) / n.
In Python 2 when one of the arguments is float, the calculation will be carried out in float.
But doing float(total/n) won't work, since total/n has already been calculated in integers, and floating the result is already too late.

To get the average you want this:
average = float(total)/n
Some examples:
>>> float(101/2)
50.0
>>> 101/2
50
>>> float(101)/2
50.5

Related

Range Function That Prints Even Numbers From 100 To 200 Inclusive [duplicate]

This question already has answers here:
how to make a range() only even numbers in python3.3?
(2 answers)
Closed 9 months ago.
I have to create a range function so that the code prints the even numbers between 100 and 200 inclusive.
The solution I tried is
num = 100
for x in range(num % 2, 200):
print(x)
range(start,end,step)
list(range(100,200,2))

Modulo 10 for large Numbers | Checking if a number is in powers of 10 [duplicate]

This question already has answers here:
Mod function fails in python for large numbers
(2 answers)
Closed 4 years ago.
I want to check in Python if a (large integer) value is in powers of 10. Normally I would simply check the modulo 10 of the value. This works fine for values of up to 1.E+22, after that, it returns weird values:
lowInteger = 1.E12
highInteger = 1.E23
print(lowInteger % 10) #as expected returns 0
>>> 0.0
print(highInteger % 10) #returns 2.0 instead of 0.0, 1.E23 returns 3.0, etc
>>> 2.0
The floating point number 1.E23 is not a power of 10. It is the nearest representable number to the power of 10 you wanted. Its actual value is
>>> int(1e23)
99999999999999991611392
If you want exact integers, use ints, not floats. You want 10**23.
>>> 10**23
100000000000000000000000
Also, if you want to check whether a number is a power of 10, x % 10 == 0 is the wrong check anyway, because that's checking whether the number is a multiple of 10.

python - Sum of digits in 2^1000? [duplicate]

This question already has an answer here:
Is Python incorrectly handling this "arbitrary precision integer"?
(1 answer)
Closed 4 years ago.
This is my code in python but the answer it gives is not correct according to projecteuler.net.
a = 2**1000
total = 0
while a >= 1:
temp = a % 10
total = total + temp
a = int(a/10)
print(total)
It gives an output 1189. Am I making some mistake?
Your logic is fine. The problem is that 2 ** 1000 is too big for all the digits to fit into a float, so the number gets rounded when you do a = int(a/10). A Python float only has 53 bits of precision, you can read about it in the official tutorial article: Floating Point Arithmetic: Issues and Limitations, and on Wikipedia: Double-precision floating-point format. Also see Is floating point math broken?.
This is 2 ** 1000
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
But print(format(2**1000 / 10, 'f')) gives us this:
1071508607186267380429101388171324322483904737701556012694158454746129413355810495130824665231870799934327252763807170417136096893411236061781867579266085792026680021578208129860941078404632071895251811587214122307926025420797364998626502669722909817741077261714977537247847201331018951634334519394304.000000
You can see that the digits start going wrong after 10715086071862673.
So you need to use integer arithmetic, which in Python has arbitrary precision (only limited by how much memory Python can access). To do that, use the // floor division operator.
a = 2**1000
total = 0
while a >= 1:
temp = a % 10
total = total + temp
a = a // 10
print(total)
output
1366
We can condense that code a little by using augmented assignment operators.
a = 2**1000
total = 0
while a:
total += a % 10
a //= 10
print(total)
Here's a faster way. Convert a to a string then convert each digit back to int and sum them. I use bit shifting to compute a because it's faster than exponentiation.
print(sum(int(u) for u in str(1 << 1000)))

Computing PI in Python 2, how to stop answer truncating [duplicate]

This question already has answers here:
How to define a decimal class holding 1000 digits in python?
(4 answers)
Closed 7 years ago.
please go easy on me, I've been learning Python about a week!
I thought I'd try calculating Pi using the Rumanujan formula. I am confident I was able to code that correctly.
My answer is truncating and I'd like it to be represented with 200 dp. In C I'd use malloc to do this perhaps but I understand that Python doesn't work that way.
The learning point I'd like to take away from this is: Is the truncation caused by the limit of representing a float, and if so is it possible to fix?
Thanks.
import math
from decimal import *
getcontext().prec = 200
def iterate(n):
sum = 0
Decimal(sum)
sum = (math.factorial(4*n))
sum = (sum/math.pow(math.factorial(n), 4))
sum = sum*((26390*n +1103)/math.pow(396, (4*n)))
return sum
ans=0
Decimal(ans)
print "Choose the number of iterations:\n"
itnum = int(raw_input())
for n in range (0, itnum+1):
this_iteration = 0
Decimal(this_iteration)
this_iteration = iterate(n)
ans = ans + this_iteration
ans = ans*(math.pow(8, 0.5)/9801)
ans = 1/ans
print "%.200f" % ans
Your snippet
sum = 0
Decimal(sum)
leaves sum set to the int 0, and computes and throws away a Decimal equivalent. Use, instead, an assignment statement:
sum = Decimal(0)
Next, you'll need to ensure every intermediate result is also converted appropriately to Decimal (and floats by default are not).
Personally, I'd recommend using gmpy2 instead, but then, I'm biased:-).

python simple percentage calculation returning 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 8 years ago.
Okay this seems to be really trivial but I'm not able to figure this out.
I need to do a basic percentage calculation.
This is my code:
corr = 205
score = 100 * (corr / 225 )
print score
But the result is 0.
How come? There aren't a whole of different ways to write this, but I did shuffle this around and tried adding int()s and float()s, but the results was always 0.
Adding on to #Germano's answer,
Python2.7
>>> corr = 205
>>> score = 100 * (corr / 225)
>>> print score
0
Python3 fixes the automatic casting.
>>> corr = 205
>>> score = 100 * (corr / 225)
>>> print(score)
91.11111111111111
See How can I force division to be floating point? Division keeps rounding down to 0
You should convert corr to a float, that is where you get the unexpected int
corr = 205
score = 100 * (float(corr) / 225)
print score
>>> 91.11111111111111
Although everyone else has a correct answer, I'd like to point out you can just add .0 and it will be a float automatically.
corr = 205.0
score = 100 * (corr / 225 )
print score
As well as converting corr to float:
>>> float(corr) / 255
0.9111111111111111
You can also refer to the denominator as a float, which will mean the result is also a float:
>>> corr / 225
0
>>> corr / 225.0
0.9111111111111111

Categories

Resources