调用二分法求根函数并调用求解python中的任意函数
Calling a bisection method root finiding function and calingit to solve any function in python
我已经编写了一个通用二分法来求所提供函数的根,我想调用它来求解二次函数。这是我的 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
请帮我修正错误,谢谢
root_bisection
期待一个函数作为它的第一个参数。你应该这样称呼它:
func = root_bisection(function, 0, 1)
此外,您在 function
的定义中有错别字。将 x
替换为 y
.
作为一般性建议:永远不要 from libraryXYZ import *
,只导入您真正需要的函数。这使代码更具可读性。
我已经编写了一个通用二分法来求所提供函数的根,我想调用它来求解二次函数。这是我的 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
请帮我修正错误,谢谢
root_bisection
期待一个函数作为它的第一个参数。你应该这样称呼它:
func = root_bisection(function, 0, 1)
此外,您在 function
的定义中有错别字。将 x
替换为 y
.
作为一般性建议:永远不要 from libraryXYZ import *
,只导入您真正需要的函数。这使代码更具可读性。