1. 程式人生 > >java 版本二重積分計算

java 版本二重積分計算

public abstract class Calculate {
	public Calculate(){
		
	}
	public abstract double function(double x);
	
	public abstract double function(double x,double y);
	
	/**
	 * 牛頓-萊布尼茲積分
	 * */
	public double Integral(double x1,double x2,double eps){
		if(x2==x1){
			try {
				throw new Exception("不好意思,貌似不可以這麼積分");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		double length=Math.abs(x1-x2);
		int n=(int)(1/eps);
		double steps=length/n;
		double sum=0;
		for(int i=0;i<n;i++){
			double height=function(x1+steps*i);
			double square=steps*height;
			sum=sum+square;
		}
		return sum;
	}
	public double Integral(double x1,double x2,double y1,double y2,double eps){
		double lengthY=Math.abs(y2-y1);
		double lengthX=Math.abs(x2-x1);
		int n=(int)(1/eps);
		double stepsY=lengthY/n;
		double stepsX=lengthX/n;
		double sum=0;
		for(int i=0;i<n;i++){
			for(int j=0;j<n;j++){
				double heightY=function(x1+stepsX*i,y1+stepsY*j);
				double squareY=heightY*stepsY*stepsX;
				sum=sum+squareY;
			}
		}
		return sum;
	}
}

public class test{
	public static void main(String[] args){
		class C extends Calculate{

			@Override
			public double function(double x) {
				// TODO Auto-generated method stub
				return x;
			}

			@Override
			public double function(double x, double y) {
				return E.e(x)*E.e(y);
			}
		}
		C c=new C();
		double r=c.Integral(0, 1,0,1,0.00005);
		System.out.println((E.e(1)-1)*(E.e(1)-1));
		System.out.println(r);
	}
}