Reputation: 1043
I am trying to find the sum for series : 1 − 1 / 2 + 1 / 3 − 1 / 4 + · · · + 1 / 99 − 1 / 100 ** 2
with python.
My code is -
psum = 0
nsum = 0
for k in range(1,100):
if k%2 == 0:
nsum += 1.0/k
else:
psum += 1.0/k
print psum - nsum - 1.0/100**2
The output is 0.69807217931
I don't have the answer and just want to verify if I am doing it right.
This is not a homework question but just random Python practice.
Upvotes: 4
Views: 8414
Reputation: 921
Here's my suggestion. little but more LOC then @steveha but more generic.
getx=lambda x:(1.0/x)*((-1)**((x%2)+1))
num=100
sum((getx(x) for x in xrange(1,num)))+getx(num)**2
0.688172179310195
Upvotes: 0
Reputation: 76695
sum(1.0/k if k % 2 else -1.0/k for k in xrange(1, 100)) - 1.0/100**2
The above code does the same thing as your code, and gets the same answer.
Why does the series use 1/k from 1 through 99, and then use 1/k**2 just for k == 100?
Upvotes: 3
Reputation: 71
The easiest way to see if you're doing it right is to try it with a much shorter series, one that you can check by hand. For example, use range(1, 5) and see if it gives the answer you expect.
For style tips, you can use xrange instead of range. xrange is nice because it just returns each number as it's needed, while range creates a big list of all the numbers. If you did this for range(1, 1000000), it would use up a lot of memory, while xrange wouldn't.
You could also get away with just one variable for the sum instead of two, I think.
Upvotes: 1
Reputation: 61478
That works fine, but why not just use one "summing" variable (call it total
, as a matter of good practice, since there is a built-in called sum
which you don't really want to hide), and actually add or subtract from it at each step?
Alternately (pun intended!), actually use that sum
function. The range
function can be used to skip every other number, too.
>>> sum(1.0/k for k in range(1, 100, 2)) - sum(1.0/k for k in range(2, 100, 2)) - (1.0/100**2)
0.6980721793101952
Or, as steveha shows, you can use logic to sort out whether to add or subtract the number based on whether it's divisible by 2, and handle it with a "weighted" sum (adding 1.0/k or -1.0/k as appropriate). This is why you should learn more math as a programmer :)
Upvotes: 5