替换numpy数组中的行时出错 [英] Error when replacing row in numpy array
问题描述
我遇到了一个问题,尝试用新行替换numpy二维数组中的行.
I am hitting a problem trying to replace a row in a numpy 2-d array with a new row.
我正试图编写一个函数,以 m
矩阵(n个长度为m的长度向量的样本)取 n
,并返回一个正交基数集.对于第一步,我要计算第一行的长度,然后除以该值(标准化第一行).当我尝试将归一化的行分配回原始矩阵时,出现错误:
I am trying to write a function to take an n
by m
matrix (n samples of m-length vectors) and return an orthonormal basis set. For the first step I am calculating the length of the first row and then dividing by that value (normalizing the first row). When I try to assign the normalized row back to the original matrix, I am hitting an error:
import numpy.linalg as la
def gauss_jordan(z):
print(z[0])
print(la.norm(z[0]))
print(z[0] / la.norm(z[0])))
print((z[0] / la.norm(z[0])).shape)
z[0, :] = z[0, :] / la.norm(z[0])
print(z)
结果:
[ 1 2 -2]
3.0
[ 0.33333333 0.66666667 -0.66666667]
(3,)
[[ 0 0 0]
[-1 3 1]
[-2 1 3]
[ 1 -2 5]]
零行来自哪里?计算出的值都是正确的,但是我无法弄清楚我的作业出了什么问题.我也尝试过 z [0 ,:] = z [0]/la.norm(z [0])
.
Where is the zero row coming from? The calculated values are all correct, but I can't figure out what is wrong with my assignment. I have tried z[0,:] = z[0] / la.norm(z[0])
as well.
推荐答案
在我看来,它采用的是舍入除法而不是普通的除法.如果您尝试
It looks to me like it's taking the rounded division instead of the normal one. What happens if you try to
z = z.astype('float64')
z[0] /= la.norm(z[0])
此外,您使用的是numpy和python的哪个版本?难道是python 2.X吗?
Also, what version numpy and python are you using? Is it by any chance python 2.X ?
这篇关于替换numpy数组中的行时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!