我知道這已經在C/C++中解決了,但是我不太習慣這些語言能夠將它轉換爲python。我正在嘗試在python中創建this。我能來最接近的是這樣的:python中的分割方法函數
#This is meant to work for functions of the form x^a + b = 0
def secant(base, exp=2, it=20):
def f(x):
return x**exp - base
x1 = base/float(exp**2)
xnm1 = x1 - 5
xnm2 = x1 + 5
xn = 0
for n in range(it):
q = (xnm1-xnm2)/float(f(xnm1)-f(xnm2))
xn = xnm1 - (f(xnm1)*q)
xnm1, xnm2 = xn, xnm1
return xn
print secant(2, 2)
這將返回錯誤:
Traceback (most recent call last):
File "/Users/Joe/Desktop/secant.py", line 16, in <module>
print secant(2, 2)
File "/Users/Joe/Desktop/secant.py", line 11, in secant
q = (xnm1-xnm2)/float(f(xnm1)-f(xnm2))
ZeroDivisionError: float division by zero
我能,但是,編程的牛頓法,這是我基於這個代碼斷。如果有幫助的話,這裏是:
def newton(base, exp=2, it=20):
def f(x):
return x**exp - base
def df(x):
return exp*(x**(exp-1))
x1 = base/float(exp**2)
xnp = x1
xn = 0
for n in range(it):
xn = xnp - ((f(xnp)/df(xnp)))
xnp = xn
return xn
以下方法在20次迭代後給出12個數字的準確度的答案。任何幫助,將不勝感激。
對此不起作用的是什麼? –
不好意思。我通過零錯誤得到一個分區。 – JShoe