Exercise 1.15 #
The sine of an angle (specified in radians) can be computed by making use of the approximation $sinx≈x$ if x is sufficiently small, and the trigonometric identity
$$ sinx=3sin\frac{x}{3}−4sin^3\frac{x}{3} $$to reduce the size of the argument of sin. (For purposes of this exercise an angle is considered sufficiently small if its magnitude is not greater than 0.1 radians.) These ideas are incorporated in the following procedures:
(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)))))
- How many times is the procedure
papplied when(sine 12.15)is evaluated? - What is the order of growth in space and number of steps (as a function of
a) used by the process generated by the sine procedure when(sine a)is evaluated?
通过递归的思路,计算sin的值,计算的过程已经给出,本题的主要目标,是通过让读者分析这函数的计算过程,然后得出自己的结论。
原文以及解析 #
https://sicp-solutions.net/post/sicp-solution-exercise-1-15/
本人解析 #
这题其实比较简单, 只要代换一次就可以了
| sine递归次数 | Angle | p的调用 | 表达式 |
|---|---|---|---|
| 1 | 12.15 | 0 | (sine 12.15) |
| 2 | 4.05 | 0 | (p (sine 4.05)) |
| 3 | 1.35 | 0 | (p (p (sine 1.35))) |
| 4 | 0.45 | 0 | (p (p (p (sine 0.45)))) |
| 5 | 0.15 | 0 | (p (p (p (p (sine 0.15))))) |
| 6 | 0.05 | 0 | (p (p (p (p (p(sine 0.05)))))) |
| 7 | (p (p (p (p (p 0.05))))) |
p的调用次数 #
通过表,可以看出来,这明显是个递归,因为p被阻碍无法调用,最终递归的深度是5
12.15进行到5次的时候,value已经<0.1了
增加一些打印进行验证猜想 #
#lang racket
(define (cube x) (* x x x))
(define (p x)
(display (format "calcp\n"))
(- (* 3 x) (* 4 (cube x))))
(define (sine angle)
(display (format "~s\n" angle))
(if (not (> (abs angle) 0.1))
angle
(p (sine (/ angle 3.0)))))
(sine 12.15)
![]()
可以看到,循环的终止条件如下
$$ \frac{a}{3^n}<0.1 $$因为要不断的 循环 / 3,接下来计算下n的值,则就是代表循环的次数
$$ log(\frac{a}{0.1})空间复杂度(growth in space) #
空间复杂度,就是 $\Theta(n) = log_3(n)$
原因是需要不断进行/3操作,直到<0.1
时间复杂度(number of steps) #
时间复杂度和空间复杂度类似,都是log的
到这里,感觉高中数学也都忘记了
这个n到底该怎么算呢。。。
算了,直接放答案把
(ceiling(/ (log (/ 12.15 0.1)) (log 3)))
看懂也不容易啊