我想要一个函数(如果相关,则使用 Python 3.6+),它会按照以下方式将 float 随机舍入为整数:
给定一个实数x
,令a = floor(x)
并令b = ceil(x)
。然后,编写一个函数 s_int()
以 b - x
的概率返回 a
并返回 b
概率为 x - a
。
例如,s_int(14.8)
应该在 20% 的时间内返回 14
,在剩余的 80% 的时间内返回 15
时间。
这是我的尝试:
import math
from random import random
def s_int(x):
a = math.floor(x)
return a + ((x - a) > random())
它似乎适用于我能想到的所有情况:
In [2]: Counter(s_int(14.7) for _ in range(1000000))
Out[2]: Counter({14: 300510, 15: 699490})
In [3]: Counter(s_int(-14.7) for _ in range(1000000))
Out[3]: Counter({-15: 700133, -14: 299867})
In [4]: Counter(s_int(14) for _ in range(1000000))
Out[4]: Counter({14: 1000000})
In [5]: Counter(s_int(-14) for _ in range(1000000))
Out[5]: Counter({-14: 1000000})
In [6]: Counter(s_int(0) for _ in range(1000000))
Out[6]: Counter({0: 1000000})
这是我的问题:
是否有任何我认为此函数不起作用的边缘情况?
还有其他更简单或更优雅的解决方案吗?
可以让它运行得更快吗?
最佳答案
- 我认为没有极端情况
- 尝试使用 numpy
import numpy as np
def s_int(x):
a = np.floor(x)
b = a + 1
return (np.random.choice([a, b], p=[b - x, x - a]))
- 我认为这是一个复杂度为 O(1) 的操作。不会走得更快。
关于python - 随机将 float 舍入为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62336144/