Python program to calculate harmonic series

后端 未结 11 1887
终归单人心
终归单人心 2020-12-06 19:15

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

11条回答
  •  离开以前
    2020-12-06 19:25

    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;
         }
     }
    

提交回复
热议问题