Multiply float with very large integer in Python

In Python, is there a way to multiply float with a very large integer?

As an example, I tried it print (10**100000) * 1.414

and it gave me:

OverflowError: long int too large to convert to float

Note that the values ​​(float and large) can be anything. More importantly, I want the exact value (rounded to the nearest integer) of the expression.

Please provide any solution.

+3


source to share


4 answers


Edit 2:

Ok, I understand what you need:

import mpmath

mpmath.mp.dps = 100005
i = int(mpmath.mpf("1.414") * 10 ** 100000)

print(str(i)[:10])        # 1414000000
print(len(str(i)))        # 100001
print(str(i)[-10:])       # 0000000000
print(str(i).count("0"))  # 99997

      

And for @Stefan:



int(mpmath.mpf("1.414") * (10 ** 100000 + 1000))

      

returns

14140000000000000 ... 000000000001414     # string contains 99993 0s

      

+2


source


Convert float to integer ratio:



value = 1.414
large = 10**100000

a, b = value.as_integer_ratio()
number, residual = divmod(large * a, b)
number += residual*2 >= b   

      

+2


source


If you are looking for an exact value, it means that you must be able to access it 1.414

as a string (otherwise the value stored in memory is also imprecise).

import decimal

float_string = '1.614' # to show that rounding works
exponent = 100000
decimal.getcontext().prec = exponent + 1

c = 10 ** exponent + 1
d = decimal.Decimal(float_string) * c

print d #1614000.....000002

      

+2


source


Since you accept integer approximations, here's your own solution:

def getint(x, y, z):
    z_nu, z_de = z.as_integer_ratio()
    return ((x**y) * z_nu) // z_de

      

Using:

>>> getint(2, 3, 5.)
40

>>> getint(10, 100000, 1.414)
1413999999999999923616655905789230018854141235351562500000000...  # truncated

      

0


source







All Articles