enter image description here当我尝试找到非线性方程的根时有一些例外 我认为def f(x)的问题:先感谢您。 a = 3
def jacobian(f, x):
h = 1.0e-4
n = len(x)
Jac = zeros([n,n])
f0 = f(x)
for i in arange(0, n, 1):
tt = x[i]
x[i] = tt + h
f1= f(x)
x[i] = tt
Jac [:, i] = (f1 - f0)/h
return Jac, f0
def newton(f, x, tol=1.0e-9):
iterMax = 50
for i in range(iterMax):
Jac, fO = jacobian(f, x)
if sqrt(dot(fO, fO) / len(x)) < tol:
return x, i
dx = linalg.solve(Jac, fO)
x = x - dx
print ("Too many iterations for the Newton method")
n = 2
def f(x):
f = zeros([n])
for i in arange(0,n):
f [1] = 3*x[n-1]^2 - x*[n-1] + x[n]*2 - 1 # my two equations
f[n-1] = x[n] - math.tan(x[n-1])
return f
x0 = zeros([n])
x, iter = newton(f, x0)
答案 0 :(得分:0)
根据图像索引超出范围。我认为您的问题出在评论#my two equations
附近的两行中。当您执行x[n]
时,数组超出范围,我假设您的数组大小为2。别忘了数组的大小从0开始,所以您访问的数组越界。
def f(x):
f = zeros([n])
for i in arange(0,n):
f [1] = 3*x[n-1]^2 - x*[n-1] + x[n]*2 - 1 # my two equations - error is here when accessing x[n]
f[n-1] = x[n] - math.tan(x[n-1]) # also here, accessing x[n] again
return f