0

Ok so I made an easy script because I was lazy and just wanted to add my kilometers to it so that the needed info pops out... While I know changing the variables to int() gives me the correct info I need, without it I receive a weird output of which I do now know how it is created.. This is the script:

KMstandNu = 186645



KMsnaarhuisenterug = 18.7 * 2

KMnaarPascalenterug = 8.2 * 2

Wednesday2 = KMstandNu - KMsnaarhuisenterug

Wednesday1 = Wednesday2 - KMnaarPascalenterug

Tuesday2 = Wednesday1

Tuesday1 = Tuesday2 - KMnaarPascalenterug



print("22 oktober: " + str(Tuesday1) + " - " + str(Tuesday2))

print("23 oktober: " + str(Wednesday1) + " - " + str(Wednesday2))

output:

22 oktober: 186574.80000000002 - 186591.2
23 oktober: 186591.2 - 186607.6

Ok so which clever mind can help me out why Tuesday1 gets 9 zero's and a 2 behind the correct math???

pppery
  • 3,731
  • 22
  • 33
  • 46
Igor Markovic
  • 145
  • 1
  • 11

1 Answers1

0

It's because of floating point precision. Try using Decimal instead of float:

decimal Python docs

related question

from decimal import getcontext, Decimal

getcontext().prec = 10

KMstandNu = 186645

KMsnaarhuisenterug = Decimal(18.7) * 2

KMnaarPascalenterug = Decimal(8.2) * 2

Wednesday2 = KMstandNu - KMsnaarhuisenterug

Wednesday1 = Wednesday2 - KMnaarPascalenterug

Tuesday2 = Wednesday1

Tuesday1 = Tuesday2 - KMnaarPascalenterug


print("22 oktober: " + str(Tuesday1) + " - " + str(Tuesday2))

print("23 oktober: " + str(Wednesday1) + " - " + str(Wednesday2))

output:

22 oktober: 186574.8000 - 186591.2000

23 oktober: 186591.2000 - 186607.6000

Stefan
  • 160
  • 6
  • Thanks for your answer, I just made int's because I didn't need the decimals anyway, but I somehow found the weird length for one of the variables.. – Igor Markovic Oct 24 '19 at 21:00