私はPythonが初めてで、二分法を使用して多項式の根を見つけようとして苦労しています。これまでのところ、2つの方法があります。値 x で多項式を評価するためのもの
def eval(x, poly):
"""
Evaluate the polynomial at the value x.
poly is a list of coefficients from lowest to highest.
:param x: Argument at which to evaluate
:param poly: The polynomial coefficients, lowest order to highest
:return: The result of evaluating the polynomial at x
"""
result = poly[0]
for i in range(1, len(poly)):
result = result + poly[i] * x**i
return result
次の方法は、二分法を使用して、与えられた多項式の根を見つけることになっています
def bisection(a, b, poly, tolerance):
poly(a) <= 0
poly(b) >= 0
try:
if
"""
Assume that poly(a) <= 0 and poly(b) >= 0.
:param a: poly(a) <= 0 Raises an exception if not true
:param b: poly(b) >= 0 Raises an exception if not true
:param poly: polynomial coefficients, low order first
:param tolerance: greater than 0
:return: a value between a and b that is within tolerance of a root of the polynomial
"""
二分法を使用してルートを見つけるにはどうすればよいですか? これらをテストするためのテスト スクリプトが提供されています。
編集:私は疑似コードをたどり、これで終わりました:
def bisection(a, b, poly, tolerance):
#poly(a) <= 0
#poly(b) >= 0
difference = abs(a-b)
xmid = (a-b)/2
n = 1
nmax = 60
while n <= nmax:
mid = (a-b) / 2
if poly(mid) == 0 or (b - a)/2 < tolerance:
print(mid)
n = n + 1
if sign(poly(mid)) == sign(poly(a)):
a = mid
else:
b = mid
return xmid
これは正しいです?return xmid ステートメントのインデントエラーのため、テストできませんでした。