Does anyone know how to write a program in Python that will calculate the addition of the harmonic series. i.e. 1 + 1/2 +1/3 +1/4...
@recursive's solution is correct for a floating point approximation. If you prefer, you can get the exact answer in Python 3.0 using the fractions module:
>>> from fractions import Fraction
>>> def calc_harmonic(n):
... return sum(Fraction(1, d) for d in range(1, n + 1))
...
>>> calc_harmonic(20) # sum of the first 20 terms
Fraction(55835135, 15519504)
Note that the number of digits grows quickly so this will require a lot of memory for large n. You could also use a generator to look at the series of partial sums if you wanted to get really fancy.
The harmonic series diverges, i.e. its sum is infinity..
edit: Unless you want partial sums, but you weren't really clear about that.
How about this:
partialsum = 0
for i in xrange(1,1000000):
partialsum += 1.0 / i
print partialsum
where 1000000 is the upper bound.
Homework?
It's a divergent series, so it's impossible to sum it for all terms.
I don't know Python, but I know how to write it in Java.
public class Harmonic
{
private static final int DEFAULT_NUM_TERMS = 10;
public static void main(String[] args)
{
int numTerms = ((args.length > 0) ? Integer.parseInt(args[0]) : DEFAULT_NUM_TERMS);
System.out.println("sum of " + numTerms + " terms=" + sum(numTerms));
}
public static double sum(int numTerms)
{
double sum = 0.0;
if (numTerms > 0)
{
for (int k = 1; k <= numTerms; ++k)
{
sum += 1.0/k;
}
}
return sum;
}
}
By using the numpy
module, you can also alternatively use:
import numpy as np
def HN(n):
return sum(1/arange(1,n+1))
I add another solution, this time using recursion, to find the n-th Harmonic number.
Function Prototype: harmonic_recursive(n)
Function Parameters: n
- the n-th Harmonic number
Base case: If n
equals 1
return 1.
Recur step: If not the base case, call harmonic_recursive
for the n-1
term and add that result with 1/n
. This way we add each time the i-th term of the Harmonic series with the sum of all the previous terms until that point.
(this solution can be implemented easily in other languages too.)
harmonic_recursive(n):
if n == 1:
return 1
else:
return 1/n + harmonic_recursive(n-1)
def harmonic_recursive(n):
if n == 1:
return 1
else:
return 1.0/n + harmonic_recursive(n-1)