Monday, March 9, 2015

Trapezoidal rule in Java

Wikipedia

Calculating the integral:


/**

*

* @param x ascending order

* @param y

* @return

*/

static public double trapezoidal(double[] x, double[] y) {

    double s = 0;

    double dif = x[x.length - 1] - x[0];

    int n = x.length - 1;

    for (int i = 1; i <= n - 1; i++) {

        s += y[i];

    }

    s *= 2;

    return (dif / (2 * n)) * (y[0] + y[n] + s);

}

Calculating the maximum theoretical error:


/**

*

* @param dif total length of the strips

* @param n number of strips

* @param max max value of the 2nd derivative

* @return

*/

static public double trapError(double dif, int n, double max) {

    return ((Math.pow(dif, 3) / (12 * n * n)) * max);

}

This is part of the Definite Integral Approximations project.

No comments: