Reputation: 39
n = int(input("Enter a number:"))
while i != n:
if i>n:
print(S)
else:
if i % 2 == 0:
S -= 1 / i
i += 1
else:
S += 1 / i
i += 1
print(S)
I need to solve S = 1 - 1/2 + 1/3 - 1/4 ... 1/n, but when I enter n as 5, the output should be 0.783, instead it prints 0.583
Upvotes: 0
Views: 4744
Reputation: 19322
Here is a more pythonic way to solve this, by first creating a generator with your series, and then using sum()
.
Your series is of the following form -
Steps needed:
i: 0 -> n
n = int(input('Enter a number: '))
S = sum((1/(i+1))*(-1)**i for i in range(n))
print(S)
Enter a number: 5
0.7833333333333332
import matplotlib.pyplot as plt
#In function form
def f(n): return sum((1/(i+1))*(-1)**i for i in range(n))
#Plotting
y = [f(i+1) for i in range(100)]
plt.plot(y)
Upvotes: 1
Reputation: 11171
This is a slighter cleaner version:
n = int(input("Enter a number:"))
S = 0
for j in range(1,n+1):
if j % 2 == 0:
S -= 1/j
else:
S += 1/j
# print(j)
# print(S)
print(S)
Upvotes: 0