+ 1

python precision how to deal with without numpy

i have a written a function that returns that 2 numbers are equal if the difference between 2 numbers is <=1e-6 if abs(a - b) > eps: return False return True # 4 4.000001 in python i checked using print(f"{abs(a - b):.20f}") the difference is indeed saves as 1.e-6 something thats why i get false

7th Jan 2025, 9:37 AM
Dareen Moughrabi
Dareen Moughrabi - avatar
5 Answers
+ 1
Computers sometimes store numbers with tiny rounding errors. To compare numbers like 4 and 4.000001, which should be 'equal' for your purpose, use math.isclose(a, b, rel_tol=1e-6) instead of if abs(a - b) > 1e-6. This avoids those errors causing unexpected results because math.isclose() is designed to ignore tiny differences. PS: I had a float error in my Diablo 1 curses clone when calculating remaining HP of enemies (int/int = float). I didn't use this, but just rounded as a simple solution. In your case, you might want floats so this is a Pythonic solution. Note: Need to import math library
7th Jan 2025, 10:10 AM
PietPadda
PietPadda - avatar
+ 2
Dareen Moughrabi , if we have to handle decimals numbers without any compromises, we should not use float, but the data format `decimal`. therefore we need to import the decimal modul. see a short comparison and sample: https://sololearn.com/compiler-playground/cKNTzaOn1NV0/?ref=app
7th Jan 2025, 7:30 PM
Lothar
Lothar - avatar
+ 2
Dareen Moughrabi , here are some key points to `float vers. decimal in python` > performance: *float*: fast, since it is implemented in c and hardware-supported, suitable for most cases. *decimal*: implemented in python (software based), so lower performance, used for high precise calculations. > precision: *float*: 64-bit, with rounding errors. *decimal*: high precision, accurate for financial or math calculations. > memory consumption: *float*: fixed at 8 bytes *decimal*: i think this is more memory-consuming due to storage model and some overhead ??? > handling: *float*: is default in python, mostly supported in modules / libraries. *decimal*: a module has to be imported, needs type conversions.
8th Jan 2025, 4:56 PM
Lothar
Lothar - avatar
0
PietPadda thank you
7th Jan 2025, 10:13 AM
Dareen Moughrabi
Dareen Moughrabi - avatar
0
Lothar do we usually default to float for memory reasons so decimal is more memory heavy but other than that it does the same as float?
7th Jan 2025, 7:44 PM
Dareen Moughrabi
Dareen Moughrabi - avatar