定点求a²+a³=392的根却报OverflowError

fixed point to find root of a²+a³=392 but report OverflowError

我试图用SICP介绍的fixed_point求a²+a³=392的根1.1.3 functions as general method

#+BEGIN_SRC scheme :session sicp
(define tolerance 0.00001)

(define (fixed-point f first-guess)
  (define (close-enough? v1 v2)
    (< (abs (- v1 v2))
       tolerance))
  (define (try guess)
    (let ((next (f guess)))
      (if (close-enough? guess next)
          next
          (try next))))
  (try first-guess))
#+END_SRC

我在python中重写为:

#+begin_src ipython :session sicp :results output :tangle pySrc/sicp_fixedpoint.py
import math
tolerance = 0.00001

import math

def fixed_point(f, guess):
    while True:
        nex = f(guess)
        if abs(guess-nex) < tolerance:
            return nex
        else:
            guess = nex 

def f(x):
    return 392 / (x + x**2)
fixed_point(f, 1)
#+end_src

报错:

 OverflowError: (34, 'Numerical result out of range')

有什么问题?

我认为这道题不太适合用定点程序求解。如果您为每次迭代打印 (abs (- next guess)),您会看到该值在迭代之间 增加 ,它永远不会收敛到指定的公差 - 因此 Numerical result out of range错误。