Python Numpy-将非常小的数字视为零 [英] Python Numpy - Treat really small numbers as zero
问题描述
我想用Numpy计算奇异矩阵的行列式(行列式为0),当我打印行列式时,行列式显示的数字非常小(几乎为零= -7.09974814699e-30),但自身不为零...
I want to calculate the Determinant of a Singular Matrix (which has a 0 determinant) with Numpy and when I print the determinant it shows a really small number (which is nearly zero = -7.09974814699e-30) but not zero itself...
当我尝试使用%s,%d或%f打印行列式时,有时为零,有时为-0,有时为-7.09974814699e-30.
when I try to print the determinant either with %s, %d or %f, sometimes it's zero, sometimes -0 and sometimes -7.09974814699e-30 .
这是代码:
import numpy as np
array = np.arange(16)
array = array.reshape(4, -1)
determinant = np.linalg.det(array)
print("Determinant is %s" % determinant)
print("Determinant is %d" % determinant)
print("Determinant is %f" % determinant)
Determinant is -7.09974814699e-30
Determinant is 0
Determinant is -0.000000
我如何使Numpy将非常小的数字(例如-7.09974814699e-30)视为零并向我显示零.我还问过这个问题,如果您看一下矩阵,看到它充满了很小的数字,但不是零,它应该是一个对角矩阵,对角线上有数字,而其他地方为零...
How can I make Numpy treat really small numbers such as -7.09974814699e-30 as zero and show zero to me. I also asked this question before, if you take a look at the matrix you see that it's filled with really small numbers but not zero while it should be a diagonal matrix with numbers on the diagonal and zeros elsewhere...
谢谢...
推荐答案
>>> if np.abs(determinant) < 0.000001:
... determinant=0
...
>>> print determinant
0
对于数组,您可以使用单个操作来完成(请参见我对其他问题的回答: https://stackoverflow. com/a/36395905/5088142 )
In case of array you can do it using a single operation (see my answer to your other question: https://stackoverflow.com/a/36395905/5088142)
要将小于eps的数组元素设置为零:
To set array elements that are less than eps to zero:
array[np.abs(array) < eps] = 0
这篇关于Python Numpy-将非常小的数字视为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!