Zeahoo
V2EX  ›  编程

我这个开立方的 scheme 代码哪里有错。

  •  
  •   Zeahoo · Oct 24, 2016 · 3768 views
    This topic created in 3683 days ago, the information mentioned may be changed or developed.

    在看 SICP 这本书,做到练习 1.8 的时候,Newton method 实现的代码如下:

    (define (cubrt-iter guess x)
      (if (good-enough? guess x)
          guess
          (cubrt-iter (improve guess x)
    		 x)))
    
    (define (improve guess x)
      (third guess (/ x guess)))
    
    (define (third x y)
      (/ (+ (/ x (* y y))
    	(* 2 y))
         3))
    
    (define (good-enough? guess x)
      (< (abs (- (cube guess) x)) 0.001))
    
    (define (cube x) (* x x x))
    (define (abs x)
      (cond ((> x 0) x)
            ((= x 0) 0)
            ((< x 0) (- x)))
      )
    
    (define (cubrt x)
      (cubrt-iter 1.0 x))
    
    

    使用牛顿公式做开立方,但是不知道为什么执行的时候没有结果,大家帮我看下原因吧 :(

    Supplement 1  ·  Oct 24, 2016

    贴已经解决了,third里面的参数搞反了,正式代码解决如下:

    (define (cubrt-iter guess x)
      (if (good-enough? guess x)
          guess
          (cubrt-iter (improve guess x)
    		 x)))
    
    (define (improve guess x)
      (/ (+ (/ x (* guess guess))
    	(* 2 guess))
         3))
    
    (define (good-enough? guess x)
      (< (abs (- (cube guess) x)) 0.001))
    
    (define (cube x) (* x x x))
    
    (define (abs x)
      (cond ((> x 0) x)
            ((= x 0) 0)
            ((< x 0) (- x)))
      )
    
    (define (cubrt x)
      (cubrt-iter 1.0 x))
    
    
    3 replies  •  2016-10-24 11:02:47 +08:00
    tan90ds
    tan90ds
    Oct 24, 2016
    1
    你的 improve 函数和 third 函数有点怪,没仔细看但是感觉不像是正确的牛顿迭代法。
    Zeahoo
    Zeahoo
    OP
    Oct 24, 2016
    2
    Zeahoo
    Zeahoo
    OP
    Oct 24, 2016
    3
    @tan90ds 一脸蒙蔽,终于知道原因了, third 里面 x 和 y 的参数搞反了。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2473 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 12:34 · PVG 20:34 · LAX 04:34 · JFK 07:34
    ♥ Do have faith in what you're doing.