-1

Via panda the values in the table below are read with non existing decimal place e.g.: 0.6 is read as 0.59999999999999998 (see code below)

I would have expected to read 0.6 as 0.6.

Why is it interpreted like this and what do I have to code to get the expected behaviour?

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'))

prints to: 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

BXC_007
  • 1
  • 1
  • Can you represent 1/3 exactly in decimal? That's exactly the same problem that 0.1 has in binary. – duffymo Jan 17 '16 at 22:39

1 Answers1

0

See Why Are Floating Point Numbers Inaccurate? and for further reading What Every Computer Scientist Should Know About Floating-Point Numbers. Short version: computers don't have enough space for truly infinite precision so decimal numbers are represented in ways that have trade-offs of speed and accuracy.

For arbitrary precision decimals in Python, you need the decimal package.

Community
  • 1
  • 1
Alex Taylor
  • 8,343
  • 4
  • 25
  • 40