views:

1241

answers:

7

hi, does anyone know how to write a program in pytohn that will calculate the addition of the harmonic series. i.e.1/2 +1/3 +1/4... thanks. lincoln

+3  A: 

This ought to do the trick.

def calc_harmonic(n):
    return sum(1.0/d for d in range(2,n+1))
recursive
If you are using Python 3 you can do 1/d instead of 1.0/d
mdec
If you use xrange, this doesn't use an exorbitant amount of memory for large n
zenazn
Also note the loss of precision in using floating point numbers -- @Kiv's answer yields the exact value for all n.
cdleary
@cdleary: What are you going to do with the exact answer? The numerator and denominator grow exponentially, so using floating points is a good idea. [And it's much much faster to print an approximation; just print "ln n + 0.5772156649" -- see http://en.wikipedia.org/wiki/Euler-Mascheroni_constant ]
ShreevatsaR
+1  A: 

How about this:

partialsum = 0
for i in xrange(1,1000000):
    partialsum += 1.0 / i
print partialsum

where 1000000 is the upper bound.

zenazn
When you assign to sum, you're overwriting a builtin function. I try to avoid doing that, because it can lead to weird bugs if you try to call that function later.
recursive
Oops. I'll fix it.
zenazn
Also, another minor thing: your first term is 1/1. In the question it's 1/2.
recursive
If I remember correctly, the first term of the harmonic series is 1/1.
dancavallaro
That's how I learned it too, but the question says otherwise. Oh well.
recursive
Well, the harmonic series starts with 1, so that's where I chose to start. It's not hard to fix :)
zenazn
@zenazn: just as a Python-idiom note, if you want to use the name of a built-in function, it's customary to append an underscore to it; i.e. sum_ = 0
cdleary
+4  A: 

The harmonic series diverges, i.e. its sum is infinity..

edit: Unless you want partial sums, but you weren't really clear about that.

dancavallaro
I was assuming he was looking for a finite sub-series, since looping over the whole series would also take infinitely long.
recursive
Well, but that's a moot point - the series diverges anyway, so adding up an infinite number of terms is an exercise in futility.
dancavallaro
A: 

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;
     }
 }
duffymo
+1, why all the downvotes, children?
Ali A
It does sort of fail at being a "python program to calculate harmonic series"
J.T. Hurley
but certainly if somebody was sincere at wanting to do the calculation they could piece it together from this. [note to self: learn python]
duffymo
I think it's always nice to have an alternative perspective on things.
Ali A
Think of it as pseudo-code instead of Java.
duffymo
+10  A: 

@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.

Kiv
You have off-by-one error. `range(1, n)` produces `(n-1)` items not `n` items as required. Sum of the first 20 terms is `55835135/ 15519504`. See http://stackoverflow.com/questions/404346/python-program-to-calculate-harmonic-series#404843
J.F. Sebastian
Use xrange to prevent it from eating tons of memory
zenazn
This is Python 3.0 - xrange has been renamed range and the old memory-hungry range is gone.
Kiv
@Kiv: `range` in Python 3.0 is not just renamed `xrange` e.g., `range` accepts large integers but `xrange` doesn't.
J.F. Sebastian
You're right. Is this due to a change in the xrange code, or a consequence of unifying the int/long types? Both versions require an int argument, but the definition of an int changed.
Kiv
Both. rangeobject.c uses C's `long` type in Python 2.x and "PyLong" in py3k.
J.F. Sebastian
+1  A: 

Just a footnote on the other answers that used floating point; starting with the largest divisor and iterating downward (toward the reciprocals with largest value) will put off accumulated round-off error as much as possible.

joel.neely
+11  A: 
J.F. Sebastian