1

I have done some research throughout SO and I believe this is not a duplicate of How to get largest possible precision? (Python - Decimal) or Arithmetic precision problems with large numbers or How to store a big floating point number in python variable?

Let's say that I have this number: 11400361308443875328.123123123123

What data type can I use to store this in Python? I have tried float, decimal and the result it gives me:

x = Decimal('11400361308443875328.123123123123123') + Decimal('11400361308443875328.123123123123123')
print("{:12f}".format(x))
# 22800722616887750656.24624625

y = float(11400361308443875328.123123123123) + float(11400361308443875328.123123123123)
print("{:12f}".format(y))
# 22800722616887750656.000000

z = Decimal('0.123123123123123') + Decimal('0.123123123123123')
print("{:12f}".format(z))
# 0.246246246246246

I need the degree of precision that z has. How should I store this big number with floating precision so that I can do some mathematical operations on it? Is there some trick on how I can do this?

For the question on why I need this high degree of precision: this is a question from a coding challenge (not the actual question), and the submission is graded with a leeway of +- 10^-6 precision

grandia
  • 709
  • 7
  • 20
  • `x = Decimal('11400361308443875328.123123123123')`. Without making it a string, Decimal has no chance to save the precision as the number it gets has already lost the required precision. – matszwecja Sep 23 '22 at 13:33
  • Oops sorry that was my mistake, let me fix the question. But you make a good point there @matszwecja – grandia Sep 23 '22 at 13:40
  • If the number of floating point digits is the same in both numbers, you can remove the decimal separator via string manipulation and add the resulting integers (integers are arbitrary size in python). You can then simply add the decimal separator back in, again, using string manipulation. – Bananach Sep 23 '22 at 13:51
  • This question is answered in the *question* at the linked duplicate. The problem is a simple matter of reading the documentation, so I figured it should be easy to refer to a duplicate; but that's the best I could manage. – Karl Knechtel Sep 23 '22 at 13:56

1 Answers1

2

If decimal's default precision is not enough, you can change it by modifying value of getcontext().prec - https://docs.python.org/3/library/decimal.html#module-decimal

from decimal import Decimal, getcontext

getcontext().prec = 50

x = Decimal('11400361308443875328.123123123123123') + Decimal('11400361308443875328.123123123123123123')
print(x) # 22800722616887750656.246246246246246123
matszwecja
  • 6,357
  • 2
  • 10
  • 17