Very big number with floating point in Python

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')
# 22800722616887750656.24624625

y = float(11400361308443875328.123123123123) + float(11400361308443875328.123123123123)
# 22800722616887750656.000000

z = Decimal('0.123123123123123') + Decimal('0.123123123123123')
# 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

>Solution :

If decimal‘s default precision is not enough, you can change it by modifying value of getcontext().prec

from decimal import Decimal, getcontext

getcontext().prec = 50

x = Decimal('11400361308443875328.123123123123123') + Decimal('11400361308443875328.123123123123123123')
print(x) # 22800722616887750656.246246246246246123

Leave a Reply