def netwon(f, J, p0, tol):
for i in range(1,51):
p = p0 - J(p0)/f(p0)
if la.norm(p - p0) < tol:
break
p0 = p
return p
def JJ(x):
J = np.identity(4)
u = sum(x)
for i in range(0,4):
for j in range(0,4):
J[i][j] = J[i][j] + ((np.e**(np.cos(u))) * (np.sin(u)))
return J
netwon(f, JJ, [2.5, 2, 1.4, 9], 1*10**-12)
-
ValueError Traceback (most recent call last)
<ipython-input-58-b80f7ad38c88> in <module>()
----> 1 netwon(f, JJ, [2.5, 2, 1.4, 9], 1*10**-12)
<ipython-input-44-ae7c3122a6cf> in netwon(f, J, p0, tol)
1 def netwon(f, J, p0, tol):
2 for i in range(1,51):
----> 3 p = p0 - (J(p0)/f(p0))
4 if la.norm(p - p0) < tol:
5 break
<ipython-input-53-17a5f32512be> in JJ(x)
4 for i in range(0,4):
5 for j in range(0,4):
----> 6 J[i][j] = J[i][j] + ((np.e**(np.cos(u))) * (np.sin(u)))
7 return J
ValueError: setting an array element with a sequence.
我可以单独使用JJ:
JJ([2.5, 2, 1.4, 9])
array([[1.36222766, 0.36222766, 0.36222766, 0.36222766],
[0.36222766, 1.36222766, 0.36222766, 0.36222766],
[0.36222766, 0.36222766, 1.36222766, 0.36222766],
[0.36222766, 0.36222766, 0.36222766, 1.36222766]])
有人可以在这里发现我的错误吗,我不明白为什么JJ可以单独工作,但是在另一个函数中使用时会导致错误。
谢谢
答案 0 :(得分:1)
问题在于牛顿函数的第一次和第二次迭代之间的p0形状。第一步,它是一维数组(4,),但是将其重新分配给二维数组(4,4)。向JJ馈入二维数组时会失败,因为sum函数不会将2d数组折叠为单个值,而是将1d数组折叠为单个值。
PS。我使用的是伪f函数,因为未提供原始的f函数,但是我认为f函数不会导致结果p0的形状发生变化。
import numpy as np
def f(x):
return 1
def netwon(f, J, p0, tol):
for i in range(1,51):
p = p0 - J(p0)/f(p0)
# if la.norm(p - p0) < tol:
if i ==1: #at first iteration, p0 which used to be a (4,) array will be replaced with a (4,4)
global inspect
inspect = p
break
p0 = p
return p
def JJ(x):
J = np.identity(4)
u = sum(x)
for i in range(0,4):
for j in range(0,4):
J[i][j] = J[i][j] + ((np.e**(np.cos(u))) * (np.sin(u)))
return J
a = [2.5, 2, 1.4, 9]
netwon(f, JJ, a, 1*10**-12)
#fine till here
print(inspect) #no longer a (4,) array. It is now a (4,4)
print(sum(inspect)) #no longer a single value, but a (4,) array
u = sum(inspect)
((np.e**(np.cos(u))) * (np.sin(u))) #no longer a single value.
# J[i][j] = J[i][j] + ((np.e**(np.cos(u))) * (np.sin(u))) #1 location is now attempting to be assigned with an array
JJ(inspect) #will result in error.