gpt4 book ai didi

python - 收到错误 : can't convert expression to float

转载 作者:行者123 更新时间:2023-12-02 16:28:47 25 4
gpt4 key购买 nike

我是 python 的新手,我正在尝试查找 Christoffel symbols表面上的黎曼度量,但出现此错误:TypeError: can't convert expression to float。为简单起见,我编写了另一个错误完全相同的代码(我的基本代码很长且不可读,所以我尝试了这个示例代码来理解我的错误)。这是我的示例代码:

from sympy import *
import numpy as np

coor = symbols('x y')

x = [coor[0] ** 2, coor[1]]


christoffels = np.zeros((2,2))

for i in range(2):
for j in range(2):
christoffels[i][j] = x[i] * x[j]


print(christoffels)

你能告诉我哪里出了问题吗?

最佳答案

作业存在多个问题:

christoffels[i][j] = x[i] * x[j]

右边是symbols,左边是NumPy floats array cell。

因此 Python 很难将 symbols 转换为 float 。

TypeError: can't convert expression to float

让我们通过将矩阵定义为 sympy matrix 来修复它:

from sympy import *
import numpy as np

coor = symbols('x y')

x = [coor[0] ** 2, coor[1]]


# Create sympy array
christoffels = zeros(2,2)

for i in range(2):
for j in range(2):
# Now assignment works
# NOTE: In sympy location denoted as [i, j] and not [i][j]
christoffels[i, j] = x[i] * x[j]

# Matrix([[x**4, x**2*y], [x**2*y, y**2]])
print(christoffels)

关于python - 收到错误 : can't convert expression to float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63934990/

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