Lisp經典演算法

zhuxiaoxi發表於2018-03-26

求平方根

SUCCESSIVE AVERAGING DUE TO HERON OF ALEXANDRIA
** TO FIND AN APPROXIMATION TO SQRT(X) **

  1. MAKR A GUESS G
  2. IMPROVE THE GUESS BY AVERAGING G AND X/G
  3. KEEP IMPROVING THE GUESS UNTILE IT IS GOOD ENOUGH
  4. USE 1 AS AN INITIAL GUESS

演算法思想

(define (try guess x)
    (if (good-enough? guess x)
        guess
        (try (improve guess x) x)))
(define (sqrt x) (try 1 x))

參考程式碼

注:此程式碼來自https://blog.csdn.net/jazz_charles/article/details/48974029

(define (square x) (* x x)) //定義求平方  
(define (average x y) (/ (+ x y) 2)) //定義求平均值  
(define (sqrt x) //定義求平方根  
      (define (accurate guess) //定義判斷精確度  
           (<   (abs (-  (square guess)  x)) 0.001))  
      (define (improve guess) //定義改進近似值  
          (average x  (/ x guess)))  
      (define (sqrt-iter guess) //定義主體迭代求解  
          (if   (accurate guess)  
                 guess  
                (sqrt-iter (improve guess))))  
      (sqrt-iter 1.0))  

求兩數之和

迭代

(define (+ x y)
    (if (= x 0)
        y
        (+ (-1+ x) (1+ y))))

斐波那契數列

(define (fib n)
    (if (< n 2)
        n
        (+ (fib (- n 1))
            (fib (- n 2)))))    

求和演算法

等差數列求和

\[ \sum _{i=a}^{b}i \]

(define (sum-int a b)
    (if (> a b)
        0
        (+ a
            (sum-int (1+ a) b))))

萊布尼茨公式求π/8

\[ \sum_{i=a}^{b}\frac{i}{i(i+2)} \]

(define (pi-sum a b)
    (if (> a b)
        0
        (+ (/ 1 (* a (+ a 2))))
            (pi-sum (+ a 4) b))))

相關文章