Search code examples
pythonnumpymatrixlinear-algebradeterminants

Python Numpy - Treat really small numbers as zero


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...

when I try to print the determinant either with %s, %d, or %f, sometimes it's zero, sometimes -0 and sometimes -7.09974814699e-30 .

Here's the code:

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

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.


Solution

  • You can truncate less significant digits with np.round . But it's better do keep accuracy for float arithmetic. What you have to control is just the format of the final output, with the str.format function.

    In [7]: a=rand(12,12)
    In [8]: deta=det(a)
    #0.0063854296972496311
    
    In [10]: detar=det(a.round(3))
    # 0.0063817871557592153
    
    In [12]: '{:.5f}'.format(deta)
    Out[12]: '0.00639'
    
    In [13]: '{:.5f}'.format(detar)
    Out[13]: '0.00638'
    

    Last line shows a false result due to earlier optimization.