Input x and n and print the sum of four series
Expt. No.09
Page No.18
Sum of series
Aim
To write a Python program that inputs x and n and prints the sum of the series (a) 1 + x + x² + … + xⁿ (b) 1 − x + x² − … xⁿ (c) x + x²/2 + … + xⁿ/n (d) x + x²/2! + … + xⁿ/n!
Concepts used
Algorithm
- Input x and n.
- (a) Add x**i for i from 0 to n.
- (b) Add (-1)**i * x**i for i from 0 to n, so the sign changes each term.
- (c) Add x**i / i for i from 1 to n.
- (d) Keep a running factorial; add x**i / i! for i from 1 to n.
- Display the four sums rounded to 4 decimal places.
Program
# Sum of four series for given x and n x = float(input("Enter the value of x: "))n = int(input("Enter the value of n: ")) s1 = 0 # 1 + x + x^2 + ... + x^nfor i in range(n + 1): s1 = s1 + x ** i s2 = 0 # 1 - x + x^2 - ... x^nfor i in range(n + 1): s2 = s2 + (-1) ** i * x ** i s3 = 0 # x + x^2/2 + ... + x^n/nfor i in range(1, n + 1): s3 = s3 + x ** i / i s4 = 0 # x + x^2/2! + ... + x^n/n!fact = 1for i in range(1, n + 1): fact = fact * i s4 = s4 + x ** i / fact print("Sum of series (a):", round(s1, 4))print("Sum of series (b):", round(s2, 4))print("Sum of series (c):", round(s3, 4))print("Sum of series (d):", round(s4, 4))
A marked line continues the line above it. In your file, write it on the same line.
Output
$ python sum_of_series.py
Enter the value of x: 2
Enter the value of n: 4
Sum of series (a): 31.0
Sum of series (b): 11.0
Sum of series (c): 10.6667
Sum of series (d): 6.0
✓ Printed by running this program, not typed by hand.
Result
For x = 2 and n = 4 the sums were 31.0 (1+2+4+8+16), 11.0 (1−2+4−8+16), 10.6667 (2+2+2.6667+4) and 6.0 (2+2+1.3333+0.6667).
Viva voce: what the examiner may ask
01How does (-1) ** i make the signs alternate?
It is 1 when i is even and -1 when i is odd, so every second term is subtracted.
02Why is the factorial updated inside the loop instead of being calculated again each time?
i! = (i−1)! × i, so multiplying the previous value by i is enough. It saves a nested loop.
03Why does series (a) start the loop at 0 but series (c) at 1?
Series (a) has the term x⁰ = 1. Series (c) divides by i, and dividing by 0 would be an error.
Variations for the lab test
- Print the sum of 1 + 1/2 + 1/3 + … + 1/n.
- Print each term of series (d) as it is added.
- Find the sum of the first n odd numbers.
! Common mistake Starting
fact = 0: every product stays 0 and series (d) raises ZeroDivisionError.