python - 四舍五入到任何给定值python
问题描述
我有一个包含随机生成的值的列表。该列表的每个值对应于一个特定参数,如距离、时间等。我创建了一个函数,该函数将该列表的每个值四舍五入为用户输入的位数:
def round_list(list_x):
for i in range(0, len(list_x)):
incrementer = raw_input('Enter the increment value: ')
list_x[i] = np.round(list_x[i], int(incrementer))
return list_x
x = round_list(x)
print(x)
但这只会设置小数点对吗?如果用户希望它被四舍五入到 every0.25
或 every0.03
怎么办?我将如何整合它?我不认为round()
可以做到这一点。
解决方案
舍入到最接近的小数值(比如 0.25)可以通过除以分数,然后舍入到最接近的整数,然后乘以分数来完成。
像这样的东西:
def roundToBase(num, base):
return np.round(float(num) / base, 0) * base
print(roundToBase(1.3,0.25)) # 1.25
# also works for non-fractional bases,
# eg round to nearest multiple of 5:
print(roundToBase(26,5)) # 25
推荐阅读
- postgresql - 如何使用 Postgres 计算平均日期差
- c# - 如何配置 xUnit 测试以使用 NLog?
- qradar - 使用 API 的 IBM QRadar 搜索事件
- api - 如何从 API 发送自适应卡片
- javascript - vue.esm.js:649 [Vue 警告]:nextTick 中的错误:“TypeError:无法将对象转换为原始值”vue
- javascript - “请求”类型上不存在属性“授权”
- c# - Angular 9 / Typescript 在多个键上合并多个对象数组
- postgresql - 全文搜索:在任意数组项中查找节点值
- matlab - 如何获得两个二维矩阵的元素对之间的最大值?
- c++ - 如何使用 MySQL X Dev API ping