zoukankan      html  css  js  c++  java
  • 【SICP练习】25 练习1.31

    

    练习1.31

    题目中已经说的很清楚了,product用来返回在给定范围中各点的某个函数值的乘积。我们惊奇的发现这和前面的sum有着很大的相似,无非是将加法换成了乘法:

    (define (product term a next b)

        (if(> a b)

           1

          (* (term a)

            (product term (next a) next b))))

    既然在上一道习题中已经得出了sum的迭代版本,在这里同样也可以将它写成迭代的。

    (define (product term a next b)

       (define (product-iter a other)

           (if (> a b)

              other

              (product-iter (next a)

                            (* (term a) other))))

       (product-iter a 1))

    不怕被笑话,我还去查了factorial的中文意思。有了product来写factorial不要太容易呀,只不过要借助以下很久之前用到过的lambda。不过完全也可以用额外定义的函数实现同样的功能,只不过在函数内用lambda会使代码更加简洁。

    (define (factorial n)

       (product (lambda (x) x) 1 (lambda (x) (+ x 1)) n))

    下面我们来测试一下这个函数。

    晕倒。。。博主轻飘飘的来了一个(factorial 50)结果返回了半个屏幕宽的数字。

    话说我写到这里的时候才把a题做完,b题都没有看,没想到居然不知不觉中把b也碰巧做了。不过再看看原来a还没有写完,还要求pi的近似值。

    那么这部分的策略是将分子和分母分开来看。先来看分子,我们可以准备一个函数,有一个参数n,如果n1则返回2n是奇数则加上1n是偶数则加2。分母也可以用这种函数来产生。然后我们将左式中的4乘到右式,并且通过前面学的exact->inexact将分数转换成浮点数。最后我们就求出了pi。下面是完整的代码。

    (define (get-pi n)

      (define (get-numerator a)

           (cond((= a 1) 2)

               ((odd? a) (+ a 1))

           (else(+ a 2))))

      (define (get-denominator b)

          (cond ((odd? b) (+ b 2))

                (else (+ b 1))))

       (define (add1 c)

          (+ c 1))

     (* 4(exact->inexact  (/ (productget-numerator 1 add1 n)

                            (product get-denominator 1 add1 n)))))

    如是,我们再来检测检测。

    (get-pi 300)

    ;Value: 3.1467982645089903

    参数n越大,计算得到的pi越精确。

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

  • 相关阅读:
    解决Sublime 3提示 Sublime Text Error while loading PyV8 binary
    SQL中select与set的区别
    Microsoft Dynamics CRM 2011 安装完全教程
    sql语句优化
    CRM牛人博客
    Customize Spring @RequestParam Deserialization for Maps and/or Nested Objects
    Customize Spring @RequestParam Deserialization for Maps and/or Nested Objects
    Maven+Nexus+Jenkins+Svn+Tomcat+Sonar搭建持续集成环境(二)
    Maven+Nexus+Jenkins+Svn+Tomcat+Sonar搭建持续集成环境(二)
    使用Maven+Nexus+Jenkins+Svn+Tomcat+Sonar搭建持续集成环境(一)
  • 原文地址:https://www.cnblogs.com/NoMasp/p/4786205.html
Copyright © 2011-2022 走看看