Tuesday, March 15

Numerical Integration

Numerical integration is the approximate computation of an integral using numerical techniques.

/**# Script Name: test.java
# Script Version:
# Date: 2005-3-15
# Author: Ben@fadshop.net
# Description: Calculate Numerical Integration of a function.
# @author ben
*/

/**
* @author ben
*/

public class test {

public static double func(double x) {
return Math.exp(x*x); //e^(x^2)
}

public static void main(String[] args) {

double start, end;
double x, y, total;
double step;
double temp;

start = 0; end = 3;

total = 0;
if (start > end) { // make sure start 〈= end
temp = start;
start = end;
end = temp;
}

step = (end-start)/100.0; // if step == 0 then infinite loop.

for(x = start+step/2; x 〈 end; x+=step){
y = func(x);
total += Math.abs(y)*step;
}

System.out.println("Total=" + total);
}
}


上面是用来计算定积分的函数。例子中的ex2是不能算出积分的,所以只能用这种方法蛮解. 用来计算0-3的定积分,误差小于1%(跟MATLAB比较)

2 Comments:

At July 28, 2005 10:04 AM, Blogger xls said...

this is too slow.

 
At July 28, 2005 2:37 PM, Blogger Unknown said...

Are you bored because xys.org is down? :)

It's not slow. Actually you can adjust the "step" to make sure you get satisfied result as you want. Yes, it's a compromise.

 

<< Home