* used for computing definite integral with
* domain [a,b] with n even-grids.
例題4-1 利用梯形積分法 求 f(x)=exp(x) x=0~1 的面積
*/
import java.util.Scanner;
public class Main {
double F(double x1) {
return Math.exp(x1);
}
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
Main fun = new Main();
int n,i;
double a,b,x,tn,h, real ,sum=0.0;
//n=scanner.nextInt();
//a=scanner.nextFloat();
//b=scanner.nextFloat();
n=10;
a=0;
b=1.0;
h=(b-a)/n;
x=a;
for(i=1;i<=n-1;i++) {
x=x+h;
sum=sum+fun.F(Math.abs(x));
}
tn=((h/2.0)*(fun.F(Math.abs(a))+fun.F(Math.abs(b))+2.0*sum));
real=Math.exp(1) -1;
System.out.printf("T%d=%.6f , real value=%.6f error=%.6f \n",n,tn,real, Math.abs(tn-real));
}
}
輸出畫面
T10=1.719713 , real value=1.718282 error=0.001432
沒有留言:
張貼留言