数値積分(台形則)

/****************************/
/* 台形則                   */
/*      coded by Y.Suganuma */
/****************************/
import java.io.*;

public class Test {
	public static void main(String args[]) throws IOException
	{
		double y;

		Kansu kn = new Kansu();
		y = kn.daikei(0.0, 0.5*Math.PI, 100);

		System.out.println("result " + y);
	}
}

/****************/
/* 関数値の計算 */
/****************/
class Kansu extends Daikei
{
	double snx(double x)
	{
		double y = Math.sin(x);
		return y;
	}
}

abstract class Daikei
{
	/******************************************************/
	/* 数値積分(台形則)                                 */
	/*      x1 : 下限                                     */
	/*      x2 : 上限                                     */
	/*      n : 分割数                                    */
	/*      return : 積分値                               */
	/******************************************************/

	abstract double snx(double x);

	double daikei(double x1, double x2, int n)
	{
		double s = 0.0;
		double x, h;
		int i1;

		h = (x2 - x1) / n;
		x = x1;

		for (i1 = 0; i1 < n-1; i1++) {
			x += h;
			s += snx(x);
		}

		s = 0.5 * h * (snx(x1) + snx(x2) + 2.0 * s);

		return s;
	}
}