gpt4 book ai didi

python 浮点除法不起作用

转载 作者:行者123 更新时间:2023-12-01 04:22:22 24 4
gpt4 key购买 nike

我有一个Python代码,我想要对矩阵中的两个元素进行浮点除法。我尝试了 float() 和 from future import division 但它们都不起作用。这是我的代码。

from __future__ import division
import numpy as np

def backsub(U, b):
N = np.shape(U)[0]
x = b.copy()
x[N - 1, 0] = x[N - 1, 0] / U[N-1, N-1] #This keeps giving me integer results. No matter I do float(x[N - 1, 0]) or from __future__ import division
print x[N - 1, 0]
for i in range(N - 2, -1, -1):
for j in range(i + 1, N, 1):
x[i, 0] = x[i, 0] - U[i, j] * x[j]
x[i, 0] = x[i, 0] / U[i, i]
return x

b = np.matrix('1; 2; 3')
U = np.matrix('6, 5, 1; 0, 1, 7; 0, 0, 2')
print backsub(U, b)

输出:

1
[[ 4]
[-5]
[ 1]]

最佳答案

尝试

x[i, 0] = float(x[i, 0]) / U[i, i]

尝试一下

b = np.matrix('1; 2; 3', dtype=float)
U = np.matrix('6, 5, 1; 0, 1, 7; 0, 0, 2', dtype=float)

或者你也可以尝试

b = np.matrix([[1], [2], [3], dtype=float)
U = np.matrix([[6, 5, 1], [0, 1, 7], [0, 0, 2]], dtype=float)

希望对你有帮助。

关于python 浮点除法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33560776/

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