2

Is it possible to store more than 15 digits in a float.
For example, I have this float phi.

Example:

phi = 21.618033988749894848204586834365 # 30 decimal digits

print(phi) # -> ~21.618033988749893, 15 imprecise decimal digits

How can I guarantee I get more than 15 accurate digits from this float, without using the Decimal class?

NOTE: I know that this is not applicable, as Decimal is built into Python. I am leaving it open for reference to others with a similar situation, not realizing Decimal is a builtin.

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
CATboardBETA
  • 418
  • 6
  • 29
  • Does this answer your question? [How to print float to n decimal places including trailing 0s?](https://stackoverflow.com/questions/8568233/how-to-print-float-to-n-decimal-places-including-trailing-0s) – MisterMiyagi Dec 13 '21 at 12:27

1 Answers1

2

Floats are fixed-precision. They physically cannot store the amount of data you're trying to stuff into them. You will have to use an arbitrary-precision data type; decimal.Decimal is one, but there are others that may be more useful depending on what you're trying to do.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • I am trying to avoid having any or at least not many external modules in my code. I have been able to limit it to just typing, and I would like to keep it that way. – CATboardBETA Jan 13 '21 at 18:49
  • 2
    @CATboardBETA: `decimal` and `typing` are both standard library modules. Using them does not add any dependencies to your code. – user2357112 Jan 13 '21 at 18:51
  • Oh. I knew that was the case with typing, but was unaware it was with decimal. To clarify also, if in my input for a function I had `Union[float, SupportsFloat]`, it would support decimal, correct? – CATboardBETA Jan 13 '21 at 18:53
  • 2
    @CATboardBETA: Technically, but that annotation suggests you're planning to call `float` on the input, which would throw away all the extra precision you want. – user2357112 Jan 13 '21 at 18:55
  • Actually, I'll just do `Union[float, decimal]`, because I too stupid to think of that before. – CATboardBETA Jan 13 '21 at 19:14