scheme中的辛普森积分

本章主要内容在于将基础计算的过程抽象出来成为一个普遍流程,以此增加函数应用的普遍性,提高后续使用时的上限。
练习1.29 辛普森积分
辛普森积分的数学性比较强,重点在于抽象积分过程,对积分系数进行分类讨论。

点击查看代码
(define (even? x)
    ( = (remainder x 2) 0))
(define (cube x)
    ( * x x x))
(define (sum term a next b)
    (if ( > a b)
        0
        (+ (term a)
            (sum term (next a) next b))))
(define (simpsons f a b n)
    (define h ( / (- b a) n))
    (define (y k) (f (+ a (* k h))))
    (define (factor k)
        (cond ((or (= k 0) ( = k n)) 1) 
            ((even? k) 2)
            (else 4)))
    (define (term k) (* (factor k)(y k)))
    (define (next k) (+ k 1))
    (* ( / h 3) (sum term next n))
)

1.30 将抽象中的递归过程改写为迭代过程,练手题。

点击查看代码
(define (sum term a next b)
    (define (iter a result)
        (if ( > a b)
            result
            (iter (next a) ( + (term a) result))))
    (iter a 0))

1.31 对pi值的乘法展开过程的抽象

点击查看代码
(define (even? x)
    (= (remainder x 2.0) 0))
(define (next x) (+ x 2))
(define (f a b k n)
    (cond ((> k n) 1.0)
        ((even? k) (* (/ a b) ( f (next a) b (+ k 1) n)))
        (else (* (/ a b) ( f a (next b) (+ k 1) n)))))
(define (f 2 3 0 100))

同1.30 将乘法过程做一个迭代的改写

点击查看代码
(define (product term a next b)
    (define (iter a result))
        (if ( > a b)
            result
            (iter (next a) (* (term a) result)))
        (iter a 1))

1.32 引入combiner和null-value,将乘法和加法过程统一抽象为一个过程。

点击查看代码
(define (accmulate combiner null-value term a next b)
    (if (> a b)
        null-value
        (combiner (term a)
                    (accumulate combiner null-value (next a) next b))))

1.33中的一个实例,通过accmulate的过程结合一定的筛选方式(如prime筛选素数)进行特定范围的计算。

点击查看代码
(define (prime? n)
    ( = n (smallest-divisor n)))
(define (smallest-divisor n)
    ( find-divisor n 2))
(define (find-divisor n test-divisor)
    (cond ((> (* test-divisor test-divisor) (* n n)) n)
        ((divisor? test-divisor n) test-divisor)
        (else (find-divisor n (+ test-divisor 1)))))
(define (divisor? a b)
    ( = (remainder b a) 0))
(define (ori a) a)
(define (next a) (+ a 1))
(define (filtered-accmulate prime? combine null-value term a next b)
    (cond ((> a b) null-value)
          ((prime? a) (combine (term a)  
                        (filtered-accmulate prime? combine null-value term (next a) next b)))
          (else (filtered-accmulate prime? combine null-value term (next a) next b))))
(define (prime-sum a b)
    (filtered-accmulate prime? + 0 ori a next b))
posted @ 2025-12-03 21:40  檐上落白luckin  阅读(0)  评论(0)    收藏  举报