Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making sum 1/n^2 in Python

Tags:

python

I'm making a Python exercise for my university homework and I can't seem to figure it out. I need to make the sum of 1/n^2, n being a value introduced by the user.

Example:

user puts n=4

Program Calculates: 1+1/4+1/9+1/16= 1.42361111

This is what I have so far:

num = int(input("n: "))

sum = 0
x=1
while x<=num:
    sum=1/(x*x)
    x=x+1
    
print ("the sum is:" , sum)
like image 378
Vitoper Avatar asked Aug 03 '26 01:08

Vitoper


1 Answers

Taking all of the good advice in the comments into an answer:

  1. Don't use sum as a variable as that's already a function name in Python.
  2. You have to add sum to itself each iteration, otherwise sum is just overwritten each iteration.
  3. (Pointed out in the comments that your version is x*x which is the same as x**2. So this is a totally moot point.) I believe your denominator should be x**2 not x**x based on your first paragraph.

num = int(input("n: "))

output_sum = 0
x = 1
while x <= num:
    output_sum += 1/(x**2)
    x += 1
    
print ("the sum is:" , output_sum)

>>the sum is: 1.4236111111111112

Note: I switched from x = x+1 to the more common form x += 1. The same addition using the +=operator is being used for your output_sum as well.

like image 82
JNevill Avatar answered Aug 05 '26 14:08

JNevill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!