Beginner's Python – Computing a sum
Question:
I’m trying to compute sum_{k=1}^{M} = frac{1}{(2k)^2}
s = 0
M = 3
k = 1
for i in range(M):
s = 1/(2*k)**2
k += 1
print(s)
Terminal outputs
0.25
0.0625
0.027777777777777776
Where as I should be getting
0.340277777778
Which is the sum of the series from k = 1 M = 3, since I am pretty sure the task is not asking me to compute k = 1, 2, 3 separately like above.
Answers:
Your code is not combining the values that you calculate in each iteration of the for loop. Try something like the following:
s = 0
M = 3
for k in range(1, M+1):
s += 1 / (2*k)**2
print(s)
Note that you can use the range
function to get the values, rather than needing to have k += 1
each time
You are assigning a new value to s
every loop.
s = 0
M = 3
k = 1
for i in range(M):
s += 1/(2*k)**2
k += 1
print(s)
Output: 0.3402777777777778
sum = 0
limit = 3
for k in range(1, limit+1):
sum += 1/(2*k)**2
print(sum)
I’m trying to compute sum_{k=1}^{M} = frac{1}{(2k)^2}
s = 0
M = 3
k = 1
for i in range(M):
s = 1/(2*k)**2
k += 1
print(s)
Terminal outputs
0.25
0.0625
0.027777777777777776
Where as I should be getting
0.340277777778
Which is the sum of the series from k = 1 M = 3, since I am pretty sure the task is not asking me to compute k = 1, 2, 3 separately like above.
Your code is not combining the values that you calculate in each iteration of the for loop. Try something like the following:
s = 0
M = 3
for k in range(1, M+1):
s += 1 / (2*k)**2
print(s)
Note that you can use the range
function to get the values, rather than needing to have k += 1
each time
You are assigning a new value to s
every loop.
s = 0
M = 3
k = 1
for i in range(M):
s += 1/(2*k)**2
k += 1
print(s)
Output: 0.3402777777777778
sum = 0
limit = 3
for k in range(1, limit+1):
sum += 1/(2*k)**2
print(sum)