使用ocaml求数值积分 | 2011年06月28日
ocaml是一种实用性的函数式编程语言,函数式编程的数学定义严格,证明严谨,虽然不如perl般自由,但其简洁强大绝对令人叹服。有兴趣的童鞋可以通过下面的例子来体会。要深入这一编程语言,甚至其实现,可以看《types and programming language》
使用ocaml对以下积分求值:
首先给出vi下的源程序:

let rec summation (incr, test) (op, e) f a =
if test a then e
else op (f a) (summation (incr, test) (op, e) f (incr a));;
运行结果:
summation :
('a -> 'a) * ('a -> bool) -> ('b -> 'c -> 'c) * 'c -> ('a -> 'b) -> 'a -> 'c =
<fun>
这里,incr给出了对参数进行递增的函数,而test则是对增加后的条件进行测试 ,以确定是否进行终止。test a 为一次函数调用,incr a为一次函数调用
op为求和函数summation function
e为初始值,也即条件不满足时的返回值
let sum (op, e) f a b dx =
summation ((fun x -> x +. dx), (fun x -> x >. b)) (op, e) f a;;
运行结果:
sum :
('a -> 'b -> 'b) * 'b -> (float -> 'a) -> float -> float -> float -> 'b =
<fun>
let integrate f a b dx =
sum (prefix +., 0.) (fun x -> f(x) *. dx) a b dx;;
运行结果:
integrate : (float -> float) -> float -> float -> float -> float = <fun>
这里的fun x -> f(x) *. dx可以看作一个求面积的函数。
integrate (fun x -> 1.0 /. x) 1.0 2.0 0.001;;
运行结果:
#- : float = 0.69389724306
即得到了上面公式的积分近似值





跳到评论框添加评论
对“[转]建议腾讯收购金山软件”的评论: