Call me Walter
Call me Walter

Reputation: 43

How to divide large numbers with a floating point?

I have some large numbers (like 10000000 digits in total or more). Since I will lose precision, they are stored like strings. Lets take some 'small' numbers as an example (some numbers also can be integers):

a = 4782916578987656789087654678908765467417657489104.9486718490129876578
b = 657890876566567890.8765467890987654

I want to make some operations on them.

Division. Well, answer is 7.270075858095143e+30

Multiplicaiton: 3.1466371806949598e+66 And so on.

Desirable output is full number as string, but with given precision for floating point with trancated zeros and rest.

Example:
888888888888.23 / 2.5122217 == 353825814373.082590504959329565857965
(24 digits after 'point')`

I've tried decimals module, but it can't handle big integers: class 'decimal.DivisionImpossible and maybe something else what I'm not aware of.

Is there is a way to do it with standard library, or at least numpy. Or maybe some algorithm what I can also reproduce in some other languages like JavaScript?

Note: I know I can make Decimal.getcontext().prec = 8888888888888 or bigger, but it will took more time to calculate, and what if numbers are 1 and 1.7373 do I need to waste resources on it? Also it's precision for whole number, not only 'floating' digits.

Upvotes: 2

Views: 890

Answers (1)

David
David

Reputation: 445

The decimal module is your friend here. If you want to go wild, well...

import decimal
from decimal import Decimal
import sys

c = decimal.getcontext()
c.prec = 899_999_768
c.Emax = decimal.MAX_EMAX
c.Emin = decimal.MIN_EMIN

a = Decimal('149846549e500000')
b = Decimal('254984984e449')

d = a / b
f = a * b

Remember that c.prec gives you the number of digits that are shown when you print it. According to the documentation, the maximum number is 999999999999999999, and you are bound to the memory of your computer. In my case (my computer, actually), c.prec is a good number before the computer breaks.

If you print the results, what happens?

print(f'{d}')
print(f'{f}')

Since you want to play with big, big numbers, well, there you have it.

P.S. I am trying to write a number with 10 000 000 digits, but my text editors don't allow that... they freeze.

Upvotes: 2

Related Questions