[英]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? 在Python中,有没有办法将浮点数与一个非常大的整数相乘?
As an example, I tried print (10**100000) * 1.414
and it gave me: 作为一个例子,我尝试
print (10**100000) * 1.414
,它给了我:
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: 编辑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: 而对于@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). 如果您正在寻找确切的值,这意味着您必须能够以字符串形式访问
1.414
(否则,存储在内存中的值也不准确)。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.