首页 > 解决方案 > 你会如何在 Python 的一个范围内随机改变一个浮点数?

问题描述

下面是一个名为“inputfile”的输入文件中的浮点列表,我想遍历每个浮点并将其随机化 ± 0.100。我该怎么做呢?

 0.08777767595196
 0.41688405291929
 1.90493522025702
 -0.44512262940079
 -1.68572227053594
 -0.19769851139757
 0.61588125474274
 2.98863319423069
 -0.78312326907806
 -2.73208403405514
 -0.36006068363418

标签: pythonrandom

解决方案


input = open("inputfile", "r").readlines()
import random
noise = 0.1
output = [float(element) + random.random() * noise  * 2 - noise  for element in input ]
print(output )

output 是您要查找的列表并输入您的输入列表。

如果您的文件太大而无法存储两个数组,您可以直接修改输入文件,如下所示:

noise = 0.1    
for i in range(len(input)):
    input[i] = float(input[i]) + random.random() * noise  * 2 - noise

推荐阅读