简体   繁体   English

Python:使用Decimal对np.ndarray进行阶乘

[英]Python : doing factorial to a np.ndarray with Decimal

I am trying to make a fraction of factorials in a function. 我试图在一个函数中做一个阶乘。 This fraction contains big number so i use Decimal to pass them through, I have two list r and n that I first convert to np.array and I use scipy.misc.factorial for the factorial and try to force calculation with Decimal. 这个分数包含很大的数字,因此我使用Decimal来传递它们,我有两个列表rn首先转换为np.array然后将scipy.misc.factorial用于阶乘并尝试强制使用Decimal进行计算。

import scipy.misc as scM 导入scipy.misc作为scM

def LRT(r,n):
     return Decimal(scM.factorial(np.array(n)))/Decimal(scM.factorial(np.array(r)))

But I get the following error : 但是我收到以下错误:

    TypeError: Cannot convert array([ inf,  inf,  inf,  inf,  inf]) to Decimal

The error is logical but I don't see how I can perform my calculations with all this constraints 该错误是合乎逻辑的,但是我看不到如何在所有这些约束下执行我的计算

Edit : I use scipy.minimize to do some optimisation on this function. 编辑:我使用scipy.minimize对此功能进行一些优化。 When I try @zondo suggestion : 当我尝试@zondo建议时:

return np.array(map(Decimal, (scM.factorial(np.array(n)))))/np.array(map(Decimal, (scM.factorial(np.array(r)-1))))

I get the following error : 我收到以下错误:

decimal.InvalidOperation: (+-)INF/(+-)INF

I guess that your values are too big to fit in the numpy.float64 format. 我猜您的值太大,无法容纳numpy.float64格式。 let : 让:

n,r=nr=randint(0,1000,(2,10))   

Then : 然后 :

In [7]: scM.factorial(n)
Out[7]: 
array([              inf,               inf,               inf,
                     inf,   1.40500612e+051,               inf,
         2.48091408e+109,               inf,               inf,
         1.14628056e+170])

If it is the problem, all computations must be done with the Decimal module: 如果出现问题,则必须使用Decimal模块完成所有计算:

maxi=nr.max()+1
fact=empty(maxi,object)
fact[0]=Decimal(1) 
for i in range(1,maxi) :fact[i]=fact[i-1]*i
res = fact[n]/fact[r]

Then: 然后:

In [8]: res
Out[8]: 
array([Decimal('1.336968892230304730842136747E-1929'),
       Decimal('5.449748658873386365158990318E+1043'),
       Decimal('2.310919470411918843300593208E+1276'),
       Decimal('3.935786060399813919328612177E+1163'),
       Decimal('5.459985199929802328950162777E+1655'),
       Decimal('6.284598705467681430195924361E-2217'),
       Decimal('1.144104288612524663561821431E-1280'),
       Decimal('7.165867721516773886182595222E+1136'),
       Decimal('1.844064027516274886503591410E+530'),
       Decimal('1.596549217532394091033873077E-530')], dtype=object)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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