python - 随机将 float 舍入为整数

标签 python python-3.x floating-point integer rounding

我想要一个函数(如果相关,则使用 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})

这是我的问题:

  1. 是否有任何我认为此函数不起作用的边缘情况?

  2. 还有其他更简单或更优雅的解决方案吗?

  3. 可以让它运行得更快吗?

最佳答案

  1. 我认为没有极端情况
  2. 尝试使用 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]))
  1. 我认为这是一个复杂度为 O(1) 的操作。不会走得更快。

关于python - 随机将 float 舍入为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62336144/

相关文章:

python - 安装 Python igraph 的问题

python - 如何在Python中读取带有包装列的数据?

python - 为字典实现自定义键,以便同一类的 2 个实例匹配

python - 列表中的所有 6 数排列

python - Python 2.7 和 3.4 中的打印范围不同

Python : How to parse things such as : from, 到正文,来自带有 Python 的原始电子邮件源

python - 如何在python中使用多维字典

floating-point - 评估多项式-浮点还是优化问题?

java - 如何在 float 组中的单个元素中标记为空

c - float 如何存储在内存中?