在Lisp-Scheme语言下使用梅钦公式计算圆周率的实现代码
1706年,英国人 约翰·梅钦( John Machin) 发明了一个用于计算 值的公式:
$\frac{\pi }{4}=4arctan\frac{1}{5}-arctan\frac{1}{239}$
或者写为:
$arccot(x)=\frac{1}{x}-\frac{1}{3x^{3}}+\frac{1}{5x^{5}}-\frac{1}{7x^{7}}…$
$\pi =4 \times (4 \times arccot(5)-arccot(239))$
如果将这个公式用LISP语言来写的话,代码如下:
#lang sicp
(define (sum term a next b tot x)
(if (> a b)
tot
(sum term (next a) next b (+ tot (term a x)) x)))
(define (inc n)(+ n 1))
(define (square x)(* x x))
(define (even? n)(= (remainder n 2) 0) )
(define (fast-expt b n)
(cond ((= n 0)1)
((even? n) (square (fast-expt b (/ n 2))))
(else (* b (fast-expt b (- n 1))))))
(define (arccotx s e x)
(define (xs x)(- (+ x x) 1))
(define (fm n x)(* (xs n) (fast-expt x (xs n))))
(define (arccot-term n x)
(if (even? n)
(/ -1 (fm n x))
(/ 1 (fm n x))))
(sum arccot-term s inc e 0 x )
)
(define (arccot x)(arccotx 1 10 x))
(* 400000000000000000000000000000000000000 (-(* 4 (arccot 5)) (arccot 239)))
运行的结果为:
$314159265358979169691727961962010544814 \frac{97848506132368561104561240125046291551235003255406}{1500783245070082179576899614358406846653276715650271}$