0

I'm making a loop to see how many calories will be burned every 5 minutes (starting at 10 minutes) and ending at 30 minutes.

    x = 30
    cals = 0
    mins = 0 
    while x > 0:
        
    x -= 5
    mins += 5
    cals += 4.2
    strcals = str(format(cals, '1'))
    if mins > 5:
        print(f"After {mins} minutes, you have burned {strcals} calories")

When I run this program, it works just fine. My loops work for finding the amount of calories burned per minute and it ends at 30. However, once I reach 15 minutes something weird happens in the output

After 10 minutes, you have burned 8.4 calories
After 15 minutes, you have burned 12.600000000000001 calories
After 20 minutes, you have burned 16.8 calories

Can someone explain why I get this output from my program at 15 minutes? What can I do to fix it?

Nick
  • 1
  • 1

1 Answers1

0

why I get this output

4.2 is not encoded exactly as 4.2 since is is not exactly representable as a floating point number. Instead a nearby value is used 4.2000000000000001776....

Further, repeated summing can incur precision problems too (even if the above was exact), eventually adding up into cals renders a value near, 12.6, but not exactly.


What can I do to fix it?

  • Limit precision of output.

  • Reduce likelihood by not repeatedly incrementing. cals = min * (4.2 / 5.0).

chux - Reinstate Monica
  • 113,725
  • 11
  • 107
  • 213