码迷,mamicode.com
首页 > 其他好文 > 详细

sicp ex-2.57 多项式求导

时间:2018-12-31 11:20:56      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:函数   正文   dde   variable   can   要求   动手   ica   返回   

原书正文中列举了怎样对二项式求导的方法,本习题要求修改求导函数支持以支持多项式求导。
主要修改在于取 +/* 运算的第二个运算数:如果剩余的运算数大于1,则返回一个列表,并且在列表前加 +/* 运算符。

 

这道题在网上查了很久,没找到满意的答案,自己动手写一个,功能验证正确。

测试用例:

(derive ‘(+ y x) ‘x)
(derive ‘(+ y x 3) ‘x)
(derive ‘(+ y x (+ x 4) 3) ‘x)
(derive ‘(+ (* x x) (* 3 x) y) ‘x)
(derive ‘(+ (* x x) (* 3 x)) ‘x)
(derive ‘(+ (* x x x (+ 1 (* x x))) (* 3 x)) ‘x)

运行结果:

1
1
2
‘(+ (+ x x) 3)
‘(+ (+ x x) 3)
‘(+ (+ (* x (+ (* x (+ (* x (+ x x)) (+ 1 (* x x)))) (* x (+ 1 (* x x)))))  * x x (+ 1 (* x x)))) 3)

代码如下:

(define (derive exp var)
  (define (=number? a b)
    (and (number? a) (= a b)))
  
  (define (make-sum a b)
    (cond ((=number? a 0) b)
          ((=number? b 0) a)
          ((and (number? a) (number? b)) (+ a b))
          (else (list + a b))))
  
  (define (make-product a b)
    (cond ((=number? a 0) 0)
          ((=number? b 0) 0)
          ((=number? a 1) b)
          ((=number? b 1) a)
          ((and (number? a) (number? b)) (* a b))
          (else (list * a b))))
  
  (define (product? a)
    (if (eq? a *)
        true
        false))
  
  (define (sum? a)
    (if (eq? (car a) +)
        true
        false))
  
  (define (addend s) (cadr s))
  
  (define (make-sum-list a b)
    (if (= (length b) 1)
        (list + a (car b))
        (append (list + a ) b))
    )
  (define (augend s)
    (if (<= (length s) 3)
        (caddr s)
        (make-sum-list (caddr s) (cdddr s))))

  
  (define (make-product-list a b)
    (if (= (length b) 1)
        (list * a (car b))
        (append (list * a ) b))
    )
  
  (define (multiplier s) (cadr s))
  
  (define (multiplicand s) 
    (if (<= (length s) 3)
        (caddr s)
        (make-product-list (caddr s) (cdddr s))))
  
  (define (variable? a)
    (symbol? a))
  
  (cond ((number? exp) 0)
    ((variable? exp)
     (if (eq? exp var) 1 0))
    ((sum? exp) (make-sum (derive (addend exp) var) (derive (augend exp) var)))
    ((product? (car exp)) (make-sum (make-product (multiplier exp) (derive (multiplicand exp) var))
                       (make-product (derive (multiplier exp) var) (multiplicand exp))))))

 

sicp ex-2.57 多项式求导

标签:函数   正文   dde   variable   can   要求   动手   ica   返回   

原文地址:https://www.cnblogs.com/plumnut/p/10201522.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!