Last active
April 22, 2021 02:07
-
-
Save yanfeng42/6b6edbdc948f0725cff76eeee5bcb9f1 to your computer and use it in GitHub Desktop.
sicp1.29 通用的高阶求和算法 + 辛普森积分算法
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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 | |
|# |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
关键点: