Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
print(0.1+0.2==0.3)
#1
hi
I saw in a quiz on Instagram that wanted the result of
 print(0.1+0.2==0.3)
.
it had 4 choices:
1)True
2)False
3) machine dependence
4)...
At first glance, it seems the result is 1.
but when I ran the line, I took False.
also in idle, I have:
 0.1+0.2
Output:
0.30000000000000004
what is your opinion about it?
choice 3, machine dependence is not true?
plz,explantion.
thanks
Reply
#2
Some useful links
https://docs.python.org/3/tutorial/floatingpoint.html
https://docs.python.org/3/faq/design.html#id5
https://stackoverflow.com/q/588004/4046632
akbarza likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
https://0.30000000000000004.com/ explains it for many languages

from decimal import Decimal
a = Decimal("0.1")
b = Decimal("0.2")
x = a + b
print(x)
Output:
0.3
akbarza likes this post
Reply
#4
(Mar-04-2024, 06:59 AM)akbarza Wrote: what is your opinion about it?
1)True
2)False
3) machine dependence
4)...
choice 3, machine dependence is not true?
Choice 2 occurs for example if Python is implemented using IEEE754 with 64 bits, that is to say 11 bits of exponent and 52 bits of mantissa plus the sign bit. This is usually the case. It would also be the choice if Python was implemented using 128 bits or 256 bits.

I don't think the choice of 64 bits is enforced in the specification of the Python language.

I made tests that showed that if a machine implemented IEEE754 on 65 bits instead of 64, that is to say 53 bits of mantissa instead of 52, then on such a machine, 0.1 + 0.2 == 0.3 would be true, so Choice 3 is a valid choice since we can't exclude that someone is crazy enough to implement Python with mad architectures.
akbarza likes this post
« We can solve any problem by introducing an extra level of indirection »
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020