😳 Python says 6 - 5.7 = 0.2999999999999998 Is Python bad at maths? The first time I saw this, I thought I broke Python. 6 - 5.7 Expected: 0.3 Got: 0.2999999999999998 Turns out… Python is innocent. 🔍 The real reason: Computers don’t understand decimals the way humans do. They store numbers in binary (base-2), and decimals like 0.1, 0.2, 0.3, 5.7 cannot be stored exactly in binary. So Python stores the closest possible value. Just like: 1/3 = 0.3333... (never ends in decimal) 0.1 never ends in binary 💡 Fun fact: 0.1 + 0.2 == 0.3 # False This isn’t a Python bug. It’s a computer science reality (IEEE floating-point standard). 📌 Key takeaway: Integers → exact Floating-point numbers → approximations Once you know this, a LOT of “weird” bugs suddenly make sense. Learning Python is not just about syntax — it’s about understanding how computers think. #Python #LearningInPublic #ComputerScience #DataScience #Programming #FloatingPoint #TechInsights
No, it is not bad at mathematics and you haven't broken anything. What are you are seeing is a problem with floating point libraries which has been identified numerous times on the Internet for many years. I understand your reaction, the loss of precision is maddening, isn't it? If you're interested and you have the time I have an easy to read article here that explains the problem fully and offers a solution: https://medium.com/@mariogianota/why-you-should-abandon-floating-point-libraries-and-use-this-method-instead-for-certain-types-of-5591be108131
Didi these is the problem of infinite sequence in fractional part of the number 6-5.7=(110)-(101.10110011001100.....) and mainly it's depends on the architecture then precision which we had set under the language or externally , and there are languages other than python uses round of techniques ,, these is as good as random number generation (it's not totally random) but pseudo random (predictable or deterministic).
floating point is a solution with trade-offs. When accuracy is needed we can resort to fixed point arithmetics (for Python, see the "decimal" package: its trade-off is fixed precision) or rational data types (see module "fractions").
Haha this is actually really interesting 😄 I don’t even work with Python yet, but this post made total sense. Never thought about how decimals behave differently in binary — the 1/3 example explained it perfectly 🤯 Stuff like this really shows that computers see numbers very differently than humans do. Learned something new today, thanks for sharing 🙌
If you're interested, There is a paper titled "What Every Computer Scientist Should Know About Floating-Point Arithmetic" by David Goldberg. It is very dense and time consuming but I think it's worth it.