Change Dir

先知cd——热爱生活是一切艺术的开始

统计

留言簿(18)

积分与排名

“牛”们的博客

各个公司技术

我的链接

淘宝技术

阅读排行榜

评论排行榜

Commons Math学习笔记——函数积分

 

2.4 函数积分

看其他篇章到目录选择。

积分可以说是最常见的了,在函数的一节中我们讲过函数的微分和给定变量求值,这里我们讲讲通过函数求积分,具体的数值积分方法和应用。什么是数值积分?在数值分析中,数值积分是计算定积分数值的方法和理论。在数学分析中,给定函数的定积分的计算不总是可行的。许多定积分不能用已知的积分公式得到精确值。数值积分是利用黎曼积分等数学定义,用数值逼近的方法近似计算给定的定积分值。借助于电子计算设备,数值积分可以快速而有效地计算复杂的积分。Commons Math中的积分包analysis.integration提供了几种数值积分的实现,UnivariateRealIntegrator接口是积分包中的基础接口,该接口继承了math包中的ConvergingAlgorithm接口。具体定义了一系列方法,其中比较主要的有double integrate(UnivariateRealFunction f, double min, double max)方法,这个方法就是通过minmax设定积分区间,通过f设定被积函数,最后返回定积分值的方法。可以看到这个接口的实现是针对单变量实函数的。多元积分的实现,目前还没有看到。

其实在UnivariateRealIntegrator接口下,并不是实现类直接实现该接口,而是通过一个Abstract类来间接实现,首先UnivariateRealIntegratorImpl实现接口,然后具体的积分方法类来继承这个接口,我认为这是一种策略-模板方法模式~~~

 

那么看到了具体的结构类图。我们以辛普森法则求积分的方法为例来看看如何应用Commons Math库。具体的辛普森积分法可以见本文的参考资料。

测试代码如下,其中用到的正弦函数类在2.1节讲述函数的时候有定义,忘记的同学可以回顾一下。

 

 1/**
 2 * 
 3 */

 4package algorithm.math;
 5
 6import org.apache.commons.math.ConvergenceException;
 7import org.apache.commons.math.FunctionEvaluationException;
 8import org.apache.commons.math.analysis.DifferentiableUnivariateRealFunction;
 9import org.apache.commons.math.analysis.UnivariateRealFunction;
10import org.apache.commons.math.analysis.integration.SimpsonIntegrator;
11import org.apache.commons.math.analysis.integration.UnivariateRealIntegrator;
12
13/**
14 * @author Jia Yu
15 * @date   2010-11-22
16 */

17public class IntegrationTest {
18
19 /**
20  * @param args
21  */

22 public static void main(String[] args) {
23  // TODO Auto-generated method stub
24  integration();
25 }

26
27 private static void integration() {
28  // TODO Auto-generated method stub
29  UnivariateRealFunction f = new SinFunction();
30        UnivariateRealIntegrator integrator = new SimpsonIntegrator();
31        
32        //integrate
33        System.out.println("f(x)=sin(x)");
34        try {
35   System.out.println("integration of f(x) from 0 to Pi is "+integrator.integrate(f, 0, Math.PI));
36  }
 catch (ConvergenceException e) {
37   // TODO Auto-generated catch block
38   e.printStackTrace();
39  }
 catch (FunctionEvaluationException e) {
40   // TODO Auto-generated catch block
41   e.printStackTrace();
42  }
 catch (IllegalArgumentException e) {
43   // TODO Auto-generated catch block
44   e.printStackTrace();
45  }

46 }

47
48}

49
50


输出结果:
f(x)=sin(x)
integration of f(x) from 0 to Pi is 2.000000064530001

想扩展的同学可以直接扩展ConvergingAlgorithmImpl抽象类,实验自己的积分方法。

相关资料:

积分:http://zh.wikipedia.org/zh-cn/%E7%A7%AF%E5%88%86

辛普森积分法:http://zh.wikipedia.org/zh-cn/%E8%BE%9B%E6%99%AE%E6%A3%AE%E7%A9%8D%E5%88%86%E6%B3%95

辛普森积分法2 http://mathworld.wolfram.com/SimpsonsRule.html

Commons math包:http://commons.apache.org/math/index.html

posted on 2010-12-19 21:27 changedi 阅读(3353) 评论(0)  编辑  收藏 所属分类: 数学


只有注册用户登录后才能发表评论。


网站导航: