Sunday 31 July 2016

python - How can I round up the number of periodic digits?




I have two numbers, one I get by calculating it and the other one I bring it from the database.



calculated = 2.183333333333333
database = 2.18333333333333


But when I compare them to know if they are the same, I return False when it should be True.



There is some way to limit the number of periodic numbers, but not to affect decimals that are not periodic, for example:



2.1748888888888 -> 2.1748
1.23333333 -> 1.23

Answer



You could use the math.isclose method:



>>> from math import isclose
>>> calculated = 2.183333333333333
>>> database = 2.18333333333333
>>> isclose(calculated, database)
True


This allows for setting the relative tolerance and minimum absolute tolerance as well refer to the docs for more explanation.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...