1.31 (另一种求圆周率的算法)
1 2 3 4 5 6 7 8 | (define (product term a next b) ( if (> a b) 1 (* (term a) (product term (next a) next b))))(product (lambda (x) x) 1 (lambda (i) (+ i 1 )) 5 ) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | (define (product term a next b) (define (iter a result) ( if (> a b) result (iter (next a) (* (term a) result)))) (iter a 1 )) (define (product-normal term a next b) ( if (> a b) 1 (* (term a) (product term (next a) next b)))) (define (factorial n) (product (lambda (x) x) 1 (lambda (i) (+ i 1 )) n)) (define (numer-term i) (cond ((= i 1 ) 2 ) ((even? i) (+ i 2 )) ( else (+ i 1 )))) (define (denom-term i) ( if (odd? i) (+ i 2 ) (+ i 1 ))) (define (pi n) (* 4 (exact->inexact ; exact->inexact 函数转换除法的商,确保计算所得的结果为浮点数格式(而不是分数格式) (/ (product numer-term 1 (lambda (i) (+ i 1 )) n) (product denom-term 1 (lambda (i) (+ i 1 )) n))))) (pi 50000 ) |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步