简体   繁体   中英

Python stat_env: I keep getting a TypeError: 'decimal.Decimal' object cannot be interpreted as an integer

I cant figure out why I get:

TypeError: 'decimal.Decimal' object cannot be interpreted as an integer.

To do this I am using a statistics python environment stat_env . I suspect it's because the list S but don't know how to fix it.

It doesn't like this line:

return Decimal(Decimal(l)**Decimal(k))*Decimal(math.exp(Decimal(-l)))/Decimal(math.factorial(Decimal(k)))

Here's the full code:

import numpy as np
import math
import matplotlib
import matplotlib.pyplot as plt
from decimal import Decimal

def poisson(l,k):
    return Decimal(Decimal(l)**Decimal(k))*Decimal(math.exp(Decimal(-l)))/Decimal(math.factorial(Decimal(k)))

n=1000
p=0.003
l=n*p
S=[]

for i in range(0,n):
    S.append(poisson(l,i))

len_x=18
b=range(0,len_x+1)
plt.close('all')
plt.stem(b,S[0:len_x+1])
title='Bernoulli Trials: PMF - Poisson Approximation'
xlabel='Number of successes in n='+str(n)+' trials'
ylabel='Probability'
plt.title(title)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.xticks(b)

plt.show()

We know what line your error was on but not which actual function call was giving an error:

return Decimal(Decimal(l)**Decimal(k))*Decimal(math.exp(Decimal(-l)))/Decimal(math.factorial(Decimal(k)))

In order to determine which part failed, we can break up the expression into all separate lines, while keeping everything equivalent. Obviously the line is all one formula, but we can pre-define/pre-calculate all the various parts of the line before returning the result:

a = Decimal(l)
b = Decimal(k)
c = Decimal(a**b)
d = Decimal(-l)
e = math.exp(d)
f = Decimal(e)
g = math.factorial(b)
h = Decimal(g)
return c*f/h

When running the code now, Python tells us the exact line the error is happening on:

g = math.factorial(b)

Thus, we can determine that math.factorial() cannot accept a Decimal, and therefore requires an integer. Luckily, b corresponds to Decimal(k) , and k is an integer, so replacing that expression with math.factorial(k) fixes the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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