在 python 中是否有等效于 Perl 的大浮点数据类型?如果我在 python 中执行 factorial(500)

Is there an equivalent of Perl's big float data type in python? If I do factorial(500) in python

在 Python 中是否有与 Perl 的 BigFloat 数据类型等效的数据类型?我问的原因是我想使用它的定义 n!/k!*(n-k)!.

来计算 nCk

对于 Perl 的 BigFloat 数据类型,根据定义的计算对于任何 n 和 k 都可以正常工作。例如

阶乘(500)/阶乘(10)*阶乘(490)

当 n 和 k 是 BigFloats 时产生准确的答案。

在 Python 中,factorial(500) 和 factorial(10)*factorial(49) 都使用 Python 用于整数的任何方式给出确切答案。因此看来 python 可以进行非常高精度的算术运算。然而商

int(阶乘(500)/(阶乘(10)*阶乘(490))

接近准确答案,但还差一点?

有没有办法从 python 中得到上述表达式的准确答案?

Python 的 int 对象可以根据需要变大(仅受可用内存的限制),因此它们可用于涉及大数的计算。在 Python 2 中,有 2 种整数类型,intlong,其中 int 用于适合机器整数的值,但在 Python 3 中它们已合并为一个 int 类型。

Python 没有内置的 BigFloat 类型,但是标准库有 decimal module which can do basic arithmetic, including square roots, to any desired precision. If you need to do arbitrary precision mathematics with more functions, please see the excellent 3rd-party library, mpmath.

您可以在计算二项式系数时安全地使用 // 底除法,因为分母中的项可以保证除以分子。例如

from math import factorial

a = (factorial(500) // factorial(490)) // factorial(10)
print(a)

输出

245810588801891098700

但是,用简单的循环计算二项式系数可能比计算那些巨大的阶乘更有效。

def binomial(n, r):
    ''' Binomial coefficients '''
    if not 0 <= r <= n:
        return 0
    p = 1
    r = min(r, n - r)
    for i in range(1, r+1):
        p *= n
        p //= i
        n -= 1
    return p

# Test

print(binomial(500, 10), '\n')

for i in range(10):
    print([binomial(i, j) for j in range(i+1)])

输出

245810588801891098700 

[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]