0

I'm still very new to all this floating point thing. I need to store a very big float, like 3664210.647581261810227924465160827365 . However, when I print the value it gets modified after the 9th decimal. Could anyone explain why this happens and how can I fix it? Thanks!

x=3664210.647581261810227924465160827365
print("{0:.28f}".format(x))

and it returns:

3664210.647581261582672595977783203125
Bianca0745
  • 23
  • 5
  • The fundamental thing you need to understand is when you write a literal in *base 10*, it is not always exactly representable in *base 2* (with a limited number of decimal points), which is fundamentally how floats are stored. – juanpa.arrivillaga Feb 25 '22 at 18:46
  • @juanpa.arrivillaga yep, I know that, it's just that I don't know if I can have that large number written exactly as it is or if I should leave it "modified" – Bianca0745 Feb 25 '22 at 18:48
  • It isn't the *size* of the number that matters. This is a *fundamental* matter as it applies to these numbers which are represented in base 2. Consider a rather mundane decimal `0.1`, well, that isn't representable in base 2 (without an [infinite repeating pattern, simillar to 1/3 -> 0.33333....](https://www.wolframalpha.com/input?i=0.1+convert+to+base+2)) see what `print(f"{0.1:.28f}")` prints...which is the closest you can get with a fixed-size binary floating point (64 bit probably) – juanpa.arrivillaga Feb 25 '22 at 18:51
  • If you want an exact representation of the *decimal literal* you write in the source code, you just cannot rely on binary floating point numbers, i.e. `float`, so use `decimal.Decimal` objects. But is that actually necessary in your use-case? – juanpa.arrivillaga Feb 25 '22 at 18:53
  • @juanpa.arrivillaga yeah, I know the 0.1+0.2 story and that size does not matter, I was just wondering if I should worry about this floating point trouble when using that specific number in a problem, but I guess that the answer is that there's nothing else I can do about it – Bianca0745 Feb 25 '22 at 18:55
  • @juanpa.arrivillaga I'll give it a try, will compare the 2 ways and see what I get, thanks! – Bianca0745 Feb 25 '22 at 18:56
  • 1
    Then I'm not sure I understand your question, you ask "I was just wondering if I should worry about this floating point trouble when using that specific number in a problem" But that really is *something that you would have to say*. I don't make nor do I know what your requirements are. In any case, just remember, when you use `decimal.Decimal` you have to use a `str` object instead of a `float` object, or else the representation is lost by the time the object is created! So `decimal.Decimal('0.1')` instead of `decimal.Decimal(0.1)` – juanpa.arrivillaga Feb 25 '22 at 18:58

0 Answers0