Python 列表中的值不会在 for 循环中改变
Values in Python list won't change in for loop
我正在对某种类型的三对角矩阵进行 LU 分解,我遇到了 Python 的问题,我根本无法理解。
def trisolve2(b):
length = len(b)
# Solve Ly = b
y = b.copy()
for i in range(1, length):
print('y[' + str(i) + '] = ' + str(b[i]) + ' - (-' + str(i) + ' / (' + str(i+1)
+ ')) * ' + str(y[i-1]))
y[i] = b[i] - (-1 * i / (i+1)) * y[i-1]
print("y = " + str(y))
# Solve Ux = y
x = y.copy()
for i in range(length - 2, 0, -1):
print("x = " + str(x))
x[i] = (y[i] + x[i+1]) / ((i+2) / (i+1))
return x
test_b = np.array([[1], [0], [0], [0], [1]])
print("b = " + str(test_b))
test_x = trisolve2(test_b)
print("x = " + str(test_x))
我希望当 i = 1 时,y[i] 被分配给 1/2,它甚至看起来应该与我放在那里的打印语句一起使用,但由于某种原因我不能绕过我的头永远不会改变。 y 保持为 b,x 保持为 y 不变。输出为:
b = [[1]
[0]
[0]
[0]
[1]]
y[1] = [0] - (-1 / (2)) * [1]
y[2] = [0] - (-2 / (3)) * [0]
y[3] = [0] - (-3 / (4)) * [0]
y[4] = [1] - (-4 / (5)) * [0]
y = [[1]
[0]
[0]
[0]
[1]]
x = [[1]
[0]
[0]
[0]
[1]]
x = [[1]
[0]
[0]
[0]
[1]]
x = [[1]
[0]
[0]
[0]
[1]]
x = [[1]
[0]
[0]
[0]
[1]]```
您的 numpy 数组默认为 int32
,0.5 四舍五入为最接近的整数:1.
>> b = np.array([[1], [0], [0], [0], [1]])
>> b
array([[1],
[0],
[0],
[0],
[1]])
>> b.dtype
dtype('int32')
尝试传递 dtype
参数:
test_b = np.array([[1], [0], [0], [0], [1]], dtype=float)
我正在对某种类型的三对角矩阵进行 LU 分解,我遇到了 Python 的问题,我根本无法理解。
def trisolve2(b):
length = len(b)
# Solve Ly = b
y = b.copy()
for i in range(1, length):
print('y[' + str(i) + '] = ' + str(b[i]) + ' - (-' + str(i) + ' / (' + str(i+1)
+ ')) * ' + str(y[i-1]))
y[i] = b[i] - (-1 * i / (i+1)) * y[i-1]
print("y = " + str(y))
# Solve Ux = y
x = y.copy()
for i in range(length - 2, 0, -1):
print("x = " + str(x))
x[i] = (y[i] + x[i+1]) / ((i+2) / (i+1))
return x
test_b = np.array([[1], [0], [0], [0], [1]])
print("b = " + str(test_b))
test_x = trisolve2(test_b)
print("x = " + str(test_x))
我希望当 i = 1 时,y[i] 被分配给 1/2,它甚至看起来应该与我放在那里的打印语句一起使用,但由于某种原因我不能绕过我的头永远不会改变。 y 保持为 b,x 保持为 y 不变。输出为:
b = [[1]
[0]
[0]
[0]
[1]]
y[1] = [0] - (-1 / (2)) * [1]
y[2] = [0] - (-2 / (3)) * [0]
y[3] = [0] - (-3 / (4)) * [0]
y[4] = [1] - (-4 / (5)) * [0]
y = [[1]
[0]
[0]
[0]
[1]]
x = [[1]
[0]
[0]
[0]
[1]]
x = [[1]
[0]
[0]
[0]
[1]]
x = [[1]
[0]
[0]
[0]
[1]]
x = [[1]
[0]
[0]
[0]
[1]]```
您的 numpy 数组默认为 int32
,0.5 四舍五入为最接近的整数:1.
>> b = np.array([[1], [0], [0], [0], [1]])
>> b
array([[1],
[0],
[0],
[0],
[1]])
>> b.dtype
dtype('int32')
尝试传递 dtype
参数:
test_b = np.array([[1], [0], [0], [0], [1]], dtype=float)