Numpy元素阶矩阵的阶乘 [英] Factorial of a matrix elementwise with Numpy

查看:599
本文介绍了Numpy元素阶矩阵的阶乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to know how to calculate the factorial of a matrix elementwise. For example,

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]!.我已经尝试过类似的

would give a matrix mat2 such that mat2[i,j] = mat[i,j]!. I've tried something like

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

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

but it passes the entire matrix as argument for np.math.factorial. I've also tried to use scipy.vectorize but for matrices larger than 10x10 I get an error. This is the code I wrote:

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,所以我不明白这是什么意思.

Such an integer number would be greater than 2e9, so I don't understand what this means.

推荐答案

有一个

There's a factorial function in scipy.misc which allows element-wise computations on arrays:

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

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

The function returns an array of float values and so can compute "larger" factorials up to the accuracy floating point numbers allow:

>>> factorial(15)
array(1307674368000.0)

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

You may need to adjust the print precision of NumPy arrays if you want to avoid the number being displayed in scientific notation.

关于scipy.vectorize:OverflowError暗示某些计算的结果太大而无法存储为整数(通常为int32int64).

Regarding scipy.vectorize: the OverflowError implies that the result of some of the calculations are too big to be stored as integers (normally int32 or int64).

如果要向量化sp.math.factorial并想要任意大的整数,则需要指定该函数返回具有'object'数据类型的输出数组.例如:

If you want to vectorize sp.math.factorial and want arbitrarily large integers, you'll need to specify that the function return an output array with the 'object' datatype. For instance:

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

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

Specifying the 'object' type allows Python integers to be returned by fact. These are not limited in size and so you can calculate factorials as large as your computer's memory will permit. Be aware that arrays of this type lose some of the speed and efficiency benefits which regular NumPy arrays have.

这篇关于Numpy元素阶矩阵的阶乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆