Home > Blockchain >  S = 1 - 1/2 1/3 - 1/4 ... 1/n
S = 1 - 1/2 1/3 - 1/4 ... 1/n

Time:11-26

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

CodePudding user response:

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)

CodePudding user response:

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 -

enter image description here

Steps needed:

  1. Create a generator for the above form
  2. Use summation over the generator from 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

Plotting the function

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)

enter image description here

  • Related