-1

我写了一个通用的二分法来找到所提供函数的根,我想调用它来求解二次函数。这是我的generalroot.py

# generalroot.py
# determines the root of any general function

def root_bisection(f, a, b, tolerance=1.0e-6):
    dx = abs(b-a)
    while dx > tolerance:
        x = (a+b)/2.0

        if (f(a)*f(x)) < 0:
            b = x
        else:
            a = x
        dx = abs(b-a)
    return

现在我调用它来解决二次函数

from math import *
from generalroot import *

def function(y):
    y = y**2 + 5*x - 9
    return y

func = root_bisection(y, 0, 1)

print  'Found f(x) =0 at x = %0.8f +/- %0.8f' % ( func , tolerance)

并收到以下错误:

raceback (most recent call last):
  File "quadfrombisectionroot.py", line 8, in <module>
    func = root_bisection ( y , 0, 1)
NameError: name 'y' is not defined

请帮我解决错误,谢谢

4

1 回答 1

1

root_bisection期待一个函数作为它的第一个参数。您可能应该这样称呼它:

func = root_bisection(function, 0, 1)

此外,您的function. 替换xy

作为一般建议:永远不要from libraryXYZ import *只导入您真正需要的功能。这使代码更具可读性。

于 2016-05-21T19:42:31.880 回答