gpt4 book ai didi

python - ValueError : setting an array element with a sequence. 函数可以单独正常工作,但在另一个函数中使用时会导致错误

转载 作者:行者123 更新时间:2023-12-01 08:41:23 36 4
gpt4 key购买 nike

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

调用 newton 时抛出此错误消息:

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 可以单独工作,但在另一个函数中使用时会导致错误。

谢谢

最佳答案

问题在于牛顿函数第一次和第二次迭代之间 p0 的形状。在第一次中,它是一个一维数组 (4,),但它被重新分配给一个二维数组 (4,4)。当输入二维数组时,JJ 会失败,因为 sum 函数不会将二维数组折叠为单个值,而是将其折叠为一维数组。
附言。我使用虚拟 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.

关于python - ValueError : setting an array element with a sequence. 函数可以单独正常工作,但在另一个函数中使用时会导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53475524/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com