pythonfloating-pointdeterminants

Handling floating-point numbers in Python3


I am an experienced R user and I am trying to learn Python3 on my own since a couple of days. The way Python handles floating-point numbers is really confusing for me at the beginning. For example,

print(1.1+2.2==3.3)

will return False. I know that I can solve this "problem" how Python interprets floating-point numbers by using the decimal module.

import decimal as d
print(d.Decimal("1.1")+d.Decimal("2.2")==d.Decimal("3.3"))

will return True and this is exactly what I wanted.

But how does this work with variables or other functions ? For example, I want to calculate the determinant of the following matrix:

import numpy as np
from numpy import linalg

A = np.array([[1,2],[3,4]])
Det_A = np.linalg.det(A)
print(Det_A)

The result is -2.0000000000000004 but I want the result to be exactly -2. How can I do this ?

Please excuse my imprecise language, I am not a computer scientist. Any advice is welcome.


Solution

  • Would it be ok for your application to cast to integer? print(int(Det_A)) or to just print 2 digits after the decimal pointprint({:.2f}".format(Det_A))