A series is a sum of terms that follow a rule. This program adds up three common series with one loop: the numbers 1 to n, their squares, and the fractions 1/1 to 1/n.
The program
n = int(input("Enter n: ")) sum_n = 0 sum_squares = 0 harmonic = 0.0 for i in range(1, n + 1): sum_n += i sum_squares += i * i harmonic += 1 / i print("1 + 2 + ... + n =", sum_n) print("1² + 2² + ... + n² =", sum_squares) print(f"1 + 1/2 + ... + 1/n = {harmonic:.4f}")
Typed in this example: 10. Press Run to type your own.
Enter n: 10 1 + 2 + ... + n = 55 1² + 2² + ... + n² = 385 1 + 1/2 + ... + 1/n = 2.9290
How it works
itakes the values 1, 2, ..., n. Each pass of the loop adds the next term of each series to its total.sum_nandsum_squaresstay whole numbers.1 / iis always a float, soharmonicis a float.- The third series is called the harmonic series.
:.4fprints it with four decimal places.
Using the formulas
The first two series have formulas that give the answer with no loop: 1 + 2 + ... + n = n(n + 1) / 2, and 1² + 2² + ... + n² = n(n + 1)(2n + 1) / 6. The sum of cubes is the square of the first one. sum() with a generator gives the same results as the loop, so you can compare:
n = 10 print(sum(range(1, n + 1)), n * (n + 1) // 2) print(sum(i * i for i in range(1, n + 1)), n * (n + 1) * (2 * n + 1) // 6) print(sum(i ** 3 for i in range(1, n + 1)), (n * (n + 1) // 2) ** 2)
55 55 385 385 3025 3025
// keeps the results as whole numbers. The division is always exact, because n(n + 1) is always even. The sum of natural numbers page explains why the first formula works.
The harmonic series has no simple formula
There is no short exact formula for 1 + 1/2 + ... + 1/n. For large n, it is close to ln(n) + 0.5772, where 0.5772... is a constant called the Euler-Mascheroni constant:
import math n = 1000 harmonic = sum(1 / i for i in range(1, n + 1)) estimate = math.log(n) + 0.5772156649 print(f"Loop: {harmonic:.6f}") print(f"Estimate: {estimate:.6f}")
Loop: 7.485471 Estimate: 7.484971
The harmonic series grows without limit, but very slowly: you need more than 12,000 terms to pass 10.