【SICP练习】9 练习1.15



(define(cube x) (* x x x))

(define(p x) (- (* 3 x) (* 4 (cube x))))

(define(sine angle)

   (if (not (> (abs angle) 0.1))

       angle

       (p (sine (/ angle 3.0)))))

大家自己将题目中的代码写入Edwin中,用trace可以追踪p的调用,这种功能在Visual Studio中都有,我也是最近才知道trace的。

(trace-entryp)

;Unspecifiedreturn value

(sine12.15)

[Entering#[compound-procedure 12 p]

   Args: 4.9999999999999996e-2]

[Entering#[compound-procedure 12 p]

   Args: .1495]

[Entering#[compound-procedure 12 p]

   Args: .4351345505]

[Entering#[compound-procedure 12 p]

   Args: .9758465331678772]

[Entering#[compound-procedure 12 p]

   Args: -.7895631144708228]

;Value:-.39980345741334

由此看来p一共运行了5次。

 

大家应该都看出来了sine过程是一个递归,因此它的时间和空间复杂度都是O(loga)。每当题目中传入的参数a乘以3时,p的运行次数就会增加一次。大家可以用trace愉快的测试了。

版权声明:本文为 NoMasp柯于旺 原创文章,如需转载请联系本人。

原文地址:https://www.cnblogs.com/NoMasp/p/4786221.html