2010-04-17 64 views
2
import math 

def p(n): 
    return 393000*((288200/393000)^n * math.exp(-(288200/393000)))/math.factorial(n) 

print p(3) 

當我運行它,我得到以下錯誤信息:如何解決這個python程序?

Traceback (most recent call last): 
    File "poisson.py", line 6, in <module> 
    print p(3) 
    File "poisson.py", line 4, in p 
    return 393000*((288200/393000)^n * math.exp(-(288200/393000)))/math.factoria 
l(n) 
TypeError: unsupported operand type(s) for ^: 'int' and 'float' 
+0

而不是問,爲什麼不嘗試將表達式的部分輸入到python中,並查看哪些表達式不像您期望的那樣? – 2010-04-17 13:32:35

回答

5

**

(288200/393000)^n 

請記住更換^

288200/393000 

返回0

也許你應該嘗試使用十進制數字:

import math 

def p(n): 
    a = 393000.0 # <-- notice the .0 
    b = 288200.0 
    c = b/a 
    return a * (c**n * math.exp(-c))/ math.factorial(n) 

print p(3) 

返回:

12406.890756 
2

是在^解釋是:冪?如果是這樣,請改用**

+0

當我這樣做時,它似乎解決了它,但爲什麼答案是0.0? – neuromancer 2010-04-17 05:19:34

+0

由於整數除法;看到我編輯的答案。 – Personman 2010-04-17 05:37:20

2

您還可以使用math.pow:

>>> import math 
>>> math.pow(3,2) 
9.0 

雖然實際上它看起來也許這是不是最好的主意,因爲math.pow則多爲C擴展兼容性好,不處理所有的**做的情況:

>>> 2**3000 
1230231922161117176931558813276752514640713895736833715766118029160058800614672948775360067838593459582429649254051804908512884180898236823585082482065348331234959350355845017413023320111360666922624728239756880416434478315693675013413090757208690376793296658810662941824493488451726505303712916005346747908623702673480919353936813105736620402352744776903840477883651100322409301983488363802930540482487909763484098253940728685132044408863734754271212592471778643949486688511721051561970432780747454823776808464180697103083861812184348565522740195796682622205511845512080552010310050255801589349645928001133745474220715013683413907542779063759833876101354235184245096670042160720629411581502371248008430447184842098610320580417992206662247328722122088513643683907670360209162653670641130936997002170500675501374723998766005827579300723253474890612250135171889174899079911291512399773872178519018229989376L 

>>> import math 
>>> math.pow(2, 3000) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
OverflowError: math range error 

看到http://mail.python.org/pipermail/python-list/2003-November/236169.html的更詳細一點

編輯:在回答你的問題,爲什麼它返回0.0,那是因爲你正在籌集0到電源 - 您使用/除法,默認是整數除法並將截斷。使用from __future__ import division來獲得浮點除法。