通过熊猫,下表中的值以非现有小数位读取,例如:0.6读为0.59999999999999998(见下面的代码)
我原本希望将0.6读为0.6。
为什么它被解释为这样,我需要编码才能获得预期的行为?
ldcSc = pd.read_csv(os.path.join(basepath, 'kmod_table.csv'), skiprows=2)
ldcSc
LDC 1 2 3
0 permanent 0.6 0.6 0.50
1 long-term 0.7 0.7 0.55
2 medium-term 0.8 0.8 0.65
3 short-term 0.9 0.9 0.70
4 instantaneous 1.1 1.1 0.90
print(ldcSc.get_value((ldcSc.LDC[ldcSc.LDC == 'permanent'].index[0]), '2'))
print(ldcSc.get_value((ldcSc.LDC[ldcSc.LDC == 'short-term'].index[0]), '1'))
print(ldcSc.get_value((ldcSc.LDC[ldcSc.LDC == 'medium-term'].index[0]), '3'))
打印到: 0.6 0.9 0.65
BUT:
ldcSc.get_value((ldcSc.LDC[ldcSc.LDC == 'permanent'].index[0]), '2')
0.59999999999999998
ldcSc.get_value((ldcSc.LDC[ldcSc.LDC == 'short-term'].index[0]), '1')
0.90000000000000002
ldcSc.get_value((ldcSc.LDC[ldcSc.LDC == 'medium-term'].index[0]), '3')
0.65000000000000002
答案 0 :(得分:0)
请参阅Why Are Floating Point Numbers Inaccurate?并进一步阅读What Every Computer Scientist Should Know About Floating-Point Numbers。简短版本:计算机没有足够的空间来实现真正的无限精度,因此十进制数字的表示方式需要权衡速度和准确性。
对于Python中的任意精度小数,您需要decimal包。