Making sum 1/n^2 in pyton

Viewed 96

Im making a pyton exercise for my uni homework and 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)
4 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.

You need to say as following: sum=sum + 1/(x*x)

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

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

You can also do this by calculating the sum of a generator expression (which is about 3 times faster than other methods using while that have been proposed):

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

result = sum(1/i * 1/i for i in range(1, num+1))
    
print ("the sum is:" , result)

Just

print(3.14159**2/6)

It will be approximately correct, at least for large n.

Related