我是Python的新手,想根据几何分布生成一些数字.我发现这个代码在互联网上但不起作用:
import random
from math import ceil, log
def geometric(p):
# p should be in (0.0, 1.0].
if ((p <= 0.0) or (p >=1.0)):
raise ValueError("p must be in the interval (0.0, 1.0]")
elif p == 1.0:
# If p is exactly 1.0, then the only possible generated value is 1.
# Recognizing this case early means that we can avoid a log(0.0) later.
# The exact floating point comparison should be fine. log(eps) works just
# dandy.
return 1
# random() returns a number in [0, 1). The log() function does not
# like 0.
U = 1.0 - random.random()
# Find the corresponding geometric variate by inverting the uniform variate.
G = int(ceil(log(U) / log(1.0 - p)))
return G
p=1.0/2.0
for i in range(10):
print geometric(p)
当我尝试运行它告诉我以下错误:
File "test.py", line 8
if (p <= 0.0) or (p >=1.0):
^
IndentationError: expected an indented block
错误是什么以及如何解决?
解决方法:
在Python中,缩进很重要. PEP 8涵盖了良好的压痕风格.
以您的某个函数为例,它应如下所示:
def geometric(p):
# p should be in (0.0, 1.0].
if ((p <= 0.0) or (p >=1.0)):
raise ValueError("p must be in the interval (0.0, 1.0]")
elif p == 1.0:
# If p is exactly 1.0, then the only possible generated value is 1.
# Recognizing this case early means that we can avoid a log(0.0) later.
# The exact floating point comparison should be fine. log(eps) works just
# dandy.
return 1
如果它没有正确缩进,那么它就不是有效的Python代码.
标签:python,indentation 来源: https://codeday.me/bug/20191003/1848550.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。