Problem with '{:.4f}'.format

Hallo,
I have a python class in university and I ended up playing arround on my computer when I saw something weird.When I calculate a googol with the simple(googol=10**100) and I try to print it with print(’{:.4f}’.format(googol)) I get
10000000000000000159028911097599180468360808563945281389781327557747838772170381060813469985856815104.0000
which is not right.When I print googol with print(googol) I get
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
.I don’t get how this is happening.Can anybody help?

Your name googol is created as an integer. When you format it to use a float you lose some accuracy because you only have the exponential form. So it’s just floating point error at that point.

2 Likes

What @tgrtim said.

As a little interest point, the first int that cannot be accurately represented (based off a IEEE-754 double having 53 bits of precision) is 2^53 + 1.

print(2**53+1)
# 9007199254740993
print(float(2**53+1))
# 9007199254740992

The Python docs have a whole page on it here.

2 Likes

If anyone is interested, there’s a good explanation of why this sort of thing happens on computers in this video (33:04 to the end).

1 Like

Thank you for the video, it was really interesting.

Thank ou for your answer.I appreciate it!

Thank ou for the answer.
I appreciate you took the time!