目前,我已经尝试通过定义一个'np.arrange‘来替换x,但是我一直收到一个错误:“只有整数标量数组才能转换为标量索引”,我想我可能需要重新定义我的函数,但我希望有一种简单的方法在数组中排位,为根和迭代次数提供一系列的值。
import math
#Define Newton-Raphson method as a function using a for loop
def nraphson(fn, dfn, x, tol, maxiter):
for i in range(maxiter):
xnew = x - fn(x)/dfn(x)
if abs(xnew - x) < tol: break
x = xnew
return xnew, i
#Define f(x) and f'(x) to be used in Newton-Raphson function
y = lambda x: math.exp(x) - x**2
dy = lambda x: math.exp(x) - 2*x
#Run the Newton-Raphson method with initial x as -1 from estimate
x, n = nraphson(y, dy, -1, 0.0001, 100)
#Printing text allows us to see the value determined for the root
print("the root is %f at %d iterations." % (x,n))发布于 2021-10-14 17:39:39
由于在这个问题中,输入数组的每个单元格上的迭代次数可能不同,那么可以通过嵌套迭代来更好地解决这个问题。(嵌套用于循环),我指的是在nraphson函数上遍历每个单元格的循环。
https://stackoverflow.com/questions/69574735
复制相似问题