Vanesa Piedrahita Vanesa Piedrahita - 7 days ago 7
Python Question

Plus and minus sequence in Python

im creating a program which sums the values in a sequence, but it has alternate plus/minus.

I want to make the sum of this sequence 1-(1/3)+(1/5)-(1/7)....How can i use an alternate plus and minus just like the previous example?

Here is the code i have made so far:

s=input("Ingrese el numero de terminos a sumar:", )

sum=1.0
num=1.0

for i in xrange(1,s+1):
ident=sum/(i+(i+1.0))
sum=sum+-ident

print "La suma de los",s,"terminos es %.2f"%(sum)

Answer

You can raise -1 to the power corresponding to the index of whatever term you're on:

>>> (-1)**0
1
>>> (-1)**1
-1
>>> (-1)**2
1
>>> (-1)**3
-1
>>> (-1)**4
1

Hence, the whole summation can be simplified to

result = sum((-1)**i * 1.0/(2*i + 1) for i in xrange(s))

(You shouldn't use sum as a variable name, since the name is already taken by the built-in function sum I used above.)

Comments