SICP-Exercise 1.6

Exercise 1.6. why if needs to be provided as aspecial form. ``Why can't I just define it as an ordinary procedure in terms of cond?''

new version of if:

(define (new-if predicate then-clause else-clause)
  (cond (predicate then-clause)
        (else else-clause)))

Eva demonstrates the program for Alyssa:

(new-if (= 2 3) 0 5)
5

(new-if (= 1 1) 0 5)
0

没有必要那么复杂:

(define (iter  x)
  (new-if (#t )
      0
      (iter  x)))

(iter 2)

What happens when Alyssa attempts to use this to compute square roots?Explain.

new-if普通函数,采用应用序。求值( new-if (#t )    0    (iter  x) )时,需要先求出参数的值,而(iter  x)又进入下一轮应用序...导致超过最大递归深度,栈溢出。

if采用正则序,如果将上面的代码改成if (#t ) ,出现新的错误

换言之,在new-if (#t ) 时,完全没有机会发现那个错误。fix:if #t


Exercise 1.7.  The good-enough? test used in computing square roots will not bevery effective for finding the square roots of very small numbers.Also, in real computers, arithmetic operations are almost always performed with limited precision. This makes our test inadequate forvery large numbers. Explain these statements, with examples showinghow the test fails for small and large numbers. An alternativestrategy for implementinggood-enough? is to watch how guess changes from one iteration to the next and to stop when thechange is a very small fraction of the guess. Design a square-rootprocedure that uses this kind of end test. Does this work better forsmall and large numbers?

这个问题在一些讨论double的书中都有提到。太小的数,两次的差异可能超出double的精度,好像没有变化;太大的数,精度又不足以表示两个大数之差。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值