Skip to content

Instantly share code, notes, and snippets.

@yanfeng42
Last active April 22, 2021 02:07
Show Gist options
  • Save yanfeng42/6b6edbdc948f0725cff76eeee5bcb9f1 to your computer and use it in GitHub Desktop.
Save yanfeng42/6b6edbdc948f0725cff76eeee5bcb9f1 to your computer and use it in GitHub Desktop.
sicp1.29 通用的高阶求和算法 + 辛普森积分算法
(define (sum term a next b)
(if (> a b)
0
(+ (term a)
(sum term (next a) next b)
)
)
)
; 求立方.
(define (cube x) (* x x x))
(define (integral f a b dx)
(define (add-dx x) (+ x dx))
(* (sum f (+ a (/ dx 2.0)) add-dx b)
dx)
)
#|
> (integral cube 0 1 0.01)
0.24998750000000042
> (integral cube 0 1 0.001)
0.249999875000001
|#
; simson-rule
(define (simson-rule f a b n)
(define h (/ (- b a) n))
(define (factor k)
(cond ((or (= k 0) (= k n)) 1)
((even? k) 2)
(else 4)
)
)
(define (term k)
(* (factor k)
(f (+ a (* k h)))
)
)
(define (next k)
(+ k 1)
)
(* (/ h 3.0)
(sum term 0 next n)
)
)
#|
> (simson-rule cube 0 1 100)
0.24666666666666667
> (simson-rule cube 0 1 1000)
0.24966666666666665
|#
@yanfeng42
Copy link
Author

关键点:

  • term 用来计算真正要相加的 项.
  • next 用来计算下一个 "a" 值.

@yanfeng42
Copy link
Author

相较于社区参考答案, 我认为我的 实现, 可读性相对更好些.
ref: http://community.schemewiki.org/?sicp-ex-1.29

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment