调用二分法根定义函数和calingit来求解python中的任何函数

2024-05-21 02:12:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个求函数根的一般二分法,我想调用它来解一个二次函数。这是我的通用根.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

请帮我纠正错误,谢谢


Tags: 函数frompyimportreturndeffunctionroot
1条回答
网友
1楼 · 发布于 2024-05-21 02:12:08

root_bisection需要一个函数作为其第一个参数。你应该这样称呼它:

func = root_bisection(function, 0, 1)

此外,在function的定义中也有一个输入错误。用y替换x。你知道吗

一般的建议是:永远不要做from libraryXYZ import *,而只导入您真正需要的函数。这使得代码更具可读性。你知道吗

相关问题 更多 >