【问题标题】:Factorial of a matrix elementwise with Numpy使用 Numpy 对矩阵元素进行阶乘
【发布时间】:2015-09-01 22:47:09
【问题描述】:

我想知道如何按元素计算矩阵的阶乘。例如,

import numpy as np
mat = np.array([[1,2,3],[2,3,4]])

np.the_function_i_want(mat)

会给出一个矩阵mat2,这样mat2[i,j] = mat[i,j]!。我试过类似的东西

np.fromfunction(lambda i,j: np.math.factorial(mat[i,j]))

但它将整个矩阵作为np.math.factorial 的参数传递。我也尝试过使用scipy.vectorize,但是对于大于 10x10 的矩阵,我得到了一个错误。这是我写的代码:

import scipy as sp
javi = sp.fromfunction(lambda i,j: i+j, (15,15))
fact = sp.vectorize(sp.math.factorial)
fact(javi)

OverflowError: Python int too large to convert to C long

这样的整数会大于2e9,所以我不明白这是什么意思。

【问题讨论】:

    标签: python numpy matrix vectorization factorial


    【解决方案1】:

    scipy.misc 中有一个 factorial 函数,它允许对数组进行逐元素计算:

    >>> from scipy.misc import factorial
    >>> factorial(mat)
    array([[  1.,   2.,   6.],
           [  2.,   6.,  24.]])
    

    该函数返回一个浮点值数组,因此可以计算“更大”的阶乘,直到浮点数允许的精度:

    >>> factorial(15)
    array(1307674368000.0)
    

    如果您想避免数字以科学计数法显示,您可能需要调整 NumPy 数组的打印精度。


    关于scipy.vectorizeOverflowError 意味着某些计算的结果太大而无法存储为整数(通常是int32int64)。

    如果您想要对sp.math.factorial 进行矢量化并想要任意大的整数,您需要指定该函数返回一个具有'object' 数据类型的输出数组。例如:

    fact = sp.vectorize(sp.math.factorial, otypes='O')
    

    指定'object' 类型允许fact 返回Python 整数。它们的大小不受限制,因此您可以计算出计算机内存允许的最大因子。请注意,这种类型的数组失去了常规 NumPy 数组所具有的一些速度和效率优势。

    【讨论】:

    • 感谢您的帮助!这非常有用。
    • @JavierGarcia:没问题!我很高兴能帮上忙。
    • 对于 scipy >= 1.0.0 factorial from scipy.misc 已弃用。必须改用scipy.special.factorial
    猜你喜欢
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 1970-01-01
    • 2015-08-29
    • 1970-01-01
    • 2012-07-10
    • 2013-01-06
    • 2019-03-31
    相关资源
    最近更新 更多