Harmonic.java


Below is the syntax highlighted version of Harmonic.java from §2.2 Libraries.


/******************************************************************************
 *  Compilation:  javac Harmonic.java
 *  Execution:    java Harmonic n
 *
 *  Prints the nth harmonic number: 1/1 + 1/2 + ... + 1/n.
 *
 *  % java Harmonic 10
 *  2.9289682539682538
 *
 *  % java Harmonic 10000
 *  9.787606036044348
 *
 ******************************************************************************/

public class Harmonic {

    // returns the nth Harmonic number
    public static double harmonic(int n) {
        if (n < 1000) return harmonicSmall(n);
        else          return harmonicLarge(n);
    }

    // compute nth Harmonic number when n is small
    public static double harmonicSmall(int n) {
        double sum = 0.0;
        for (int i = 1; i <= n; i++)
            sum += 1.0 / i;
        return sum;
    }

    // returns the nth Harmonic number when n is large
    public static double harmonicLarge(int n) {

        // Euler-Mascheroni constant (http://en.wikipedia.org/wiki/Euler-Mascheroni_constant)
        double GAMMA = 0.577215664901532;

        return Math.log(n) + GAMMA + 1.0/(2.0*n) - 1.0/(12.0*n*n) + 1.0/(120.0*n*n*n*n);
    }

    public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);
        StdOut.println(harmonic(n));
    }

}


Copyright © 2000–2022, Robert Sedgewick and Kevin Wayne.
Last updated: Thu Aug 11 10:17:58 EDT 2022.