数値積分(シンプソン則)

/****************************/
/* シンプソン則             */
/*      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.simpson(0.0, 0.5*Math.PI, 100);

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

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

abstract class Simpson {

	/*******************************************************/
	/* 数値積分(シンプソン則)                            */
	/*      x1 : 下限                                      */
	/*      x2 : 上限                                      */
	/*      n : 分割数                                     */
	/*      return : 積分値                                */
	/*******************************************************/

	abstract double snx(double x);

	double simpson(double x1, double x2, int n)
	{
		double s1 = 0.0;
		double s2 = 0.0;
		double s, x, h, h2;

		h  = (x2 - x1) / n;
		h2 = 2.0 * h;

		for (x = x1+h; x < x2; x += h2)
			s1 += snx(x);

		for (x = x1+h2; x < x2-h; x += h2)
			s2 += snx(x);

		s = h * (snx(x1) + snx(x2) + 4.0 * s1 + 2.0 * s2) / 3.0;

		return s;
	}
}