[英]How can I adjust this Newton-Raphson for loop to include a range of values for my initial guess so that it prints the number of iterations for each?
I currently have this, I have tried to replace x by defining an 'np.arrange' to do this but keep getting an error that says "only integer scalar arrays can be converted to a scalar index", I think I may need to redefine my function but was hoping there was an easy way to slot in an array to give me a range of values for root and the number of iterations.我目前有这个,我试图通过定义一个 'np.arrange' 来替换 x 来做到这一点,但不断收到一个错误,提示“只有整数标量数组可以转换为标量索引”,我想我可能需要重新定义我的函数,但希望有一种简单的方法可以插入数组,以便为我提供 root 的一系列值和迭代次数。
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))
As in this problem the number of iterations on each cell of input array may be different, then it may better to solve the problem by nested iterations.由于在这个问题中输入数组的每个单元格的迭代次数可能不同,那么最好通过嵌套迭代来解决问题。 (nested for loops), I mean a loop iterating over each cell of input over
nraphson
function. (嵌套 for 循环),我的意思是在
nraphson
函数上迭代输入的每个单元格的循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.