【发布时间】:2019-10-19 16:25:59
【问题描述】:
我正在阅读、处理和拟合一些在不同温度下收集的数据。对于每一组,测得的温度都有一点波动,所以我通过取温度平均值对结果进行了分组。然后我要求用户通过 raw_input 选择感兴趣的温度(例如丢弃嘈杂的温度),并使用这些索引来定位将要拟合的数据。问题是浮点平均数和用户指示的数字使用不同的表示,因此无法比较(参见Python - round a float to 2 digits)。
下面是我的代码的一个示例:
# Example of temperatures on my data set
T = [25.99545, 25.99702, 25.9982, 25.99859, 25.9986, 25.99899, 25.99899, 25.99899, 25.99899, 25.99899, 25.99899, 25.99938, 25.99938, 26.00016, 26.00056, 26.00056, 26.00056, 26.00056, 26.00056, 26.00095, 26.00095, 26.00095, 26.00134, 26.00134, 26.00134, 26.00174, 26.00213, 26.00252, 27.998, 27.99846, 27.99846, 27.99891, 27.99891, 27.99891, 27.99935, 27.99935, 27.99936, 27.9998, 27.9998, 27.9998, 27.99981, 27.99981, 28.00025, 28.00025, 28.00026, 28.00026, 28.0007, 28.0007, 28.0007, 28.0007, 28.00114, 28.00115, 28.00115, 28.00115, 28.00204, 28.00249, 29.99771, 29.99822, 29.99822, 29.99822, 29.99873, 29.99873, 29.99873, 29.99923, 29.99923, 29.99924, 29.99974, 29.99974, 29.99975, 29.99975, 29.99975, 30.00026, 30.00026, 30.00026, 30.00026, 30.00076, 30.00076, 30.00127, 30.00127, 30.00178, 30.00178, 30.00178, 30.00229, 30.00229, 31.99801, 31.99858, 31.99858, 31.99858, 31.99858, 31.99858, 31.99916, 31.99916, 31.99916, 31.99916, 31.99973, 32.00029, 32.0003, 32.0003, 32.0003, 32.0003, 32.0003, 32.00086, 32.00086, 32.00087, 32.00087, 32.00143, 32.00143, 32.00143, 32.002, 32.00201, 32.00257, 32.00372 ]
av_T = [ 25.999885000000003, 28.000059642857156, 30.000000357142863, 32.000254285714284 ] # Average of temperatures
rounded_T = [ round(x,2) for x in av_T ]
selected_T = [ 26.0, 30.0 ] # User selection of temperatures
if selected_T not in rounded_T: # Check the user indicates valid temperatures
print('The selected temperature is not in your experimental set')
exit()
由于无法比较它们的表示,我的代码总是卡在这一点上。 另外,请注意,即使我不四舍五入 av_T 和
selected_T = [ 25.999885000000003, 30.000000357142863 ]
我得到相同的行为。 有没有办法在不使用小数精度的情况下进行这种比较?
【问题讨论】:
-
如果我正确理解您的问题,您希望您的
rounded_T数组为[26.0, 28.0, 30.0, 32.0]?您可以通过舍入到 1 位而不是 2 位来做到这一点。所以它将是[round(x,1) for x in av_T]。
标签: python list member conditional-operator