简体   繁体   中英

Multiply a float with a very large integer in Python

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

As an example, I tried print (10**100000) * 1.414 and it gave me:

OverflowError: long int too large to convert to float

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

Please provide any solution.

Edit 2:

Ok, I see what you're after:

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

Convert the float to an integer ratio:

value = 1.414
large = 10**100000

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

If you're looking for the exact value, this means you must have access to 1.414 as a string (otherwise, the value stored in memory isn't exact either).

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

Since you accept integer approximations, here is a native solution:

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

Usage:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM