〖数学算法〗积分算法(一)
http://blog.csdn.net/zmazon/article/details/8560759
当我上小学的时,就学习了球的体积公式V=(4/3)πR³,当时觉得它实在太神奇了,是不是求得这个公式的人把一个铁球熔成铁水,放在一个矩形容器中求的?直到大上学才知道是利用积分算得的,当然微积分这个东西对于包括我在内的广大同学们来说可能是恨大于爱,但不可否认是积分在几乎所有理工学科都有着无可替代的作用,所以博主就写一写求积分的算法,由于算法过多,为了避免篇幅过长,给读者造成疲劳感,我决定分4篇写积分算法。
1.随机投点法(蒙特卡洛算法)
- public class JiFen {
- public static void main(String[] args){
- int N = 1000000;
- int count = 0;
- for(int i = 0; i < N; i++){
- double x = Math.random();
- double y = Math.random();
- if(f(x) >= y)
- count++;
- }
- System.out.println((double)count/N);
- }
- private static double f(double x) {
- return x*x;
- }
- }
输出:0.333302
- public class JiFen_toudian2 {
- public static void main(String[] args){
- double a = 0;
- double b = 1;
- double area = getArea(a,b);
- System.out.println(area);
- }
- public static double getArea(double a, double b){
- int sign = 1;//正负号标志位
- if(a > b){
- double t = a;
- a = b;
- b = t;
- sign = –1;
- }
- int N = 10000;
- double sum = 0;
- for(int i = 0; i < N; i++){
- double x = a + (b-a)*Math.random();//随机生成1个在(a,b)范围内的点
- sum += f(x);
- }
- return (sum * (b-a)/N) * sign;
- }
- private static double f(double x) {
- return x*x;
- }
- }
输出:0.33966325465503505
3.定义求积分法
- public class JiFen3 {
- /**
- * @param args
- */
- public static void main(String[] args) {
- double a;
- double b;
- double y;
- a = 0;
- b = 1;
- y = getArea(a, b);
- System.out.println(y);
- }
- static double f(double x){
- return x*x;
- }
- static double getArea(double a, double b){
- int sign = 1;
- if(a > b){
- double t = a;
- a = b;
- b = t;
- sign = –1;
- }
- double h;
- double x;
- double sum = 0;
- int n = 10000;
- h = Math.abs(a – b)/n;
- x = a;
- for(int i = 0; i < n; i++){
- sum += f(x) + f(x + h);
- x = x + h;
- }
- return sum * h / 2 * sign;
- }
- }
输出:0.3333333349999429
- public class Jifen_bianchang {
- static double e = 0.00001;// 误差
- public static void main(String[] args) {
- double a = 0;// 积分下限
- double b = 1;// 积分上限
- double area = getArea(a, b);
- System.out.println(area);
- }
- public static double getArea(double a, double b) {
- int sign = 1;// 正负标志位
- if (a > b) {
- double t = a;
- a = b;
- b = t;
- sign = –1;
- }
- double s1 = 0;// 前一个面积和
- double s2 = 0;// 后一个面积和
- double h = b – a;
- s2 = getOneArea(a, b, h);
- for (int i = 2; Math.abs(s1 – s2) > e; i *= 2) {
- double t = h / i;// 每个梯形高
- double sum = 0;
- double x = a;
- for (int j = 0; j < i; j++) {// 求梯形和
- sum += getOneArea(x, x + t, t);
- x = x + t;
- }
- s1 = s2;
- s2 = sum;
- }
- return sign * s2;
- }
- public static double getOneArea(double a, double b, double h) {
- return (f(a) + f(b)) * h / 2;
- }
- public static double f(double x) {
- return x * x;
- }
- }