numpy 数组在传递到循环时会丢失精度,因此比较不起作用

问题描述 投票:0回答:1

我有一个传递一维坐标数组的函数。这些是分段函数已在字典中定义的部分的末尾,并且也作为输入传入。但是,在进行比较时,数组值会更改循环中的精度,因此比较不再起作用。这是代码:

def parse_mass_data(mass_prop_file, slices, wingline, y_coords):
    data = pd.read_csv(mass_prop_file, delim_whitespace=True,index_col=False, skiprows = 10, skipfooter=(slices+5))
    cogy = []
    mass = []
    y = y_coords.astype(np.float64)
    print(y)
    for i in range(len(data['Name'].values)):
        if data['Name'][i] != 'Totals'and data['Name'][i] != 'Name':
            cogy.append(data['cgY'].values[i])
            mass.append(data['Mass'].values[i])

    cogy = np.array(list(map(float,cogy)))
    mass = np.array(list(map(float,mass)))
    x = np.zeros(len(mass))
    z = np.zeros(len(mass))

    for i in range(len(mass)):
        for j in range(len(y_coords)-1):
            if cogy[i] >= y[j] and cogy[i] < y[j+1]:
                x[i] = wingline['xy'][j][0] * cogy[i] + wingline['xy'][j][1]
                z[i] = wingline['yz'][j][0] * cogy[i] + wingline['yz'][j][1]
            # print(wingline['xy'][j],wingline['yz'][j])
            print(y[j],y[j+1])
        # print(i,x[i],cogy[i],z[i])

输出如下:

[ 0.  6. 10.]
0.0 5.999999999999999
5.999999999999999 9.999999999999998
0.0 5.999999999999999
5.999999999999999 9.999999999999998
0.0 5.999999999999999
5.999999999999999 9.999999999999998
0.0 5.999999999999999
5.999999999999999 9.999999999999998

如您所见,输入数组和循环索引中的值不匹配,导致比较无法进行。我怎样才能进行这种比较,或者有更好的方法来实现这一点?

我知道 numpy 这里有一个插值函数,但我已经有了适合这些值的方程,如果输入数据一开始不好,我可以使用该函数吗?

python pandas numpy precision
1个回答
-1
投票

由于计算机的工作方式,根据以下类似问题,这是一个已知问题:浮点数学是否已损坏?

我的解决方案是使用绝对值比较,正如该问题的已接受答案中所建议的那样。 这是编辑后的代码:

mass = np.array(list(map(float,mass)))
x = np.zeros(len(mass))
z = np.zeros(len(mass))

for i in range(len(mass)):
    for j in range(len(y_coords)-1):
        if cogy[i] >= 0:
            if abs(cogy[i] - y_coords[j] > 0.0001) and abs(cogy[i] - y_coords[j+1] <= 0.0001):
                x[i] = wingline['xy'][j][0] * cogy[i] + wingline['xy'][j][1]
                z[i] = wingline['yz'][j][0] * cogy[i] + wingline['yz'][j][1]
        else:
            if abs(cogy[i]) - abs(y_coords[j]) >= 0.0001 and abs(cogy[i]) - abs(y_coords[j+1]) < 0.0001:
                x[i] = -wingline['xy'][j][0] * cogy[i] + wingline['xy'][j][1]
                z[i] = -wingline['yz'][j][0] * cogy[i] + wingline['yz'][j][1]
© www.soinside.com 2019 - 2024. All rights reserved.