Python Floating Point Precision Errors and the Importance of math.isclose()

🔍 𝗣𝘆𝘁𝗵𝗼𝗻 𝗧𝗶𝗽: 𝗪𝗵𝘆 𝗬𝗼𝘂 𝗦𝗵𝗼𝘂𝗹𝗱𝗻’𝘁 𝗧𝗲𝘀𝘁 𝗙𝗹𝗼𝗮𝘁𝗶𝗻𝗴 𝗣𝗼𝗶𝗻𝘁 𝗡𝘂𝗺𝗯𝗲𝗿𝘀 𝗳𝗼𝗿 𝗘𝗾𝘂𝗮𝗹𝗶𝘁𝘆 I recently revisited an important lesson every Python developer should know: 𝗙𝗹𝗼𝗮𝘁𝗶𝗻𝗴 𝗽𝗼𝗶𝗻𝘁 𝗻𝘂𝗺𝗯𝗲𝗿𝘀 𝘀𝗵𝗼𝘂𝗹𝗱 𝗻𝗼𝘁 𝗯𝗲 𝘁𝗲𝘀𝘁𝗲𝗱 𝗳𝗼𝗿 𝗲𝗾𝘂𝗮𝗹𝗶𝘁𝘆 𝘂𝘀𝗶𝗻𝗴 ==. Due to the way numbers are represented in binary, certain decimal numbers can’t be stored with perfect accuracy. This means direct equality checks can lead to unexpected results. #python print(0.1 + 0.2 == 0.3)   # Output: False Even though mathematically 0.1 + 0.2 equals 0.3, Python returns False due to floating point precision errors. #python print(0.1 * 3 == 0.3)   # Output: False Multiplying 0.1 by 3 should give 0.3, but due to floating point representation, Python returns False. This issue can occur with division and more complex calculations as well. ✅ 𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻: 𝗨𝘀𝗲 𝗮 𝗧𝗼𝗹𝗲𝗿𝗮𝗻𝗰𝗲-𝗕𝗮𝘀𝗲𝗱 𝗖𝗼𝗺𝗽𝗮𝗿𝗶𝘀𝗼𝗻 The best practice is to check if numbers are “close enough,” not exactly equal. Python’s math.isclose() is perfect for this: #python import math print(math.isclose(0.1 + 0.2, 0.3))   # Output: True By using this approach, you can avoid subtle bugs and ensure your comparisons are robust. #Python #CodingTips #SoftwareEngineering #CleanCode #Programming #DeveloperTips 

The same thing happens in mysql as well for float type columns

Always be cautious while using math.isclose, a difference of 0.01 isn't true for this function , say math.isclose(0.25,0.26) is False.

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories