优化几何分布计算中的琐碎求和
def geo_dist_names(p, k):
sum = 0
for i in range(1, 4):
sum += p**i
return (p**(1+k))/sum
p 是 0 到 1 之间的浮点数,k 是 0 到 3 之间的整数。 该函数基本上只是找到与给定 p 和 k 相关的几何分布中的值,然后通过除以 的 4 个潜在值的总和来对其进行归一化k。。
它有效,但我多次调用这个函数,所以我想知道是否有更优化的方法来执行此操作?
def geo_dist_names(p, k):
sum = 0
for i in range(1, 4):
sum += p**i
return (p**(1+k))/sum
p is a float between 0 and 1 and k is an int between 0 and 3.
The function basically just find the value in a geometric distribution associated with the given p and k and then normalizes this by dividing with the sum of the 4 potential values for k.
It works, but I am calling this function many times so I wondered if there were a more optimized way of performing this operation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的代码的矢量版本是:
然而,我不确定它会比纯 python 更快,因为这里的范围很小,所以 numpy 的开销可能不可忽略。
编辑。确实,假设:
numpy 仅在范围增加时更好:
The vectorial version of your code would be:
Yet, I'm not sure that it will be faster than pure python as the range is quite small here, so the overhead of numpy is probably not negligible.
Edit. Indeed, assuming:
numpy is better only when the range increases:
不知道有没有更优化。但作为一句单行话,你可以这样写:
Don't know if it's more optimized. But as a one-liner you can wright it like this: