Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

If decimal‘s default precision is not enough, you can change it by modifying value of getcontext().prechttps://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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading