WarpPI/core/src/main/java/org/nevec/rjm/Harmonic.java

44 lines
804 B
Java
Raw Normal View History

2016-09-02 20:32:37 +02:00
package org.nevec.rjm;
2016-03-15 10:41:39 +01:00
2016-09-02 20:32:37 +02:00
/**
* Harmonic numbers.
* H(n) is the sum of the inverses of the integers from 1 to n.
2018-09-22 11:17:30 +02:00
*
2016-09-02 20:32:37 +02:00
* @since 2008-10-19
* @author Richard J. Mathar
*/
public class Harmonic {
/**
* ctor()
* Does nothing.
*/
public Harmonic() {}
2016-03-15 10:41:39 +01:00
2016-09-02 20:32:37 +02:00
/**
* The Harmonic number at the index specified
2018-09-22 11:17:30 +02:00
*
2016-09-02 20:32:37 +02:00
* @param n
* the index, non-negative.
* @return the H_1=1 for n=1, H_2=3/2 for n=2 etc.
* For values of n less than 1, zero is returned.
*/
2018-09-22 11:17:30 +02:00
public Rational at(final int n) {
2018-09-28 11:39:28 +02:00
if (n < 1) {
2018-09-22 11:17:30 +02:00
return new Rational(0, 1);
2018-09-28 11:39:28 +02:00
} else {
2016-09-02 20:32:37 +02:00
/*
* start with 1 as the result
*/
Rational a = new Rational(1, 1);
2016-03-15 10:41:39 +01:00
2016-09-02 20:32:37 +02:00
/*
* add 1/i for i=2..n
*/
2018-09-28 11:39:28 +02:00
for (int i = 2; i <= n; i++) {
2016-09-02 20:32:37 +02:00
a = a.add(new Rational(1, i));
2018-09-28 11:39:28 +02:00
}
2016-09-02 20:32:37 +02:00
return a;
}
}
2016-03-15 10:41:39 +01:00
} /* Harmonic */