Wednesday, November 28, 2018

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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...