如何修复这个python程序?

时间:2010-04-17 05:08:19

标签: python

import math

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

print p(3)

当我运行它时,我收到以下错误消息:

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'

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

^是否应该意味着取幂?如果是,请改用**

答案 2 :(得分:2)

您也可以使用math.pow:

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

虽然实际上看起来这可能不是最好的主意,因为math.pow更适用于C扩展兼容性,并且不能处理**所做的所有情况:

>>> 2**3000
1230231922161117176931558813276752514640713895736833715766118029160058800614672948775360067838593459582429649254051804908512884180898236823585082482065348331234959350355845017413023320111360666922624728239756880416434478315693675013413090757208690376793296658810662941824493488451726505303712916005346747908623702673480919353936813105736620402352744776903840477883651100322409301983488363802930540482487909763484098253940728685132044408863734754271212592471778643949486688511721051561970432780747454823776808464180697103083861812184348565522740195796682622205511845512080552010310050255801589349645928001133745474220715013683413907542779063759833876101354235184245096670042160720629411581502371248008430447184842098610320580417992206662247328722122088513643683907670360209162653670641130936997002170500675501374723998766005827579300723253474890612250135171889174899079911291512399773872178519018229989376L

VS

>>> 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来获得浮点divison。