Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python math not adding up?

trying to create a very simple clock as part of my programme , in which it increases by 0.05 seconds every 0.05 seconds. It’s not working how I intended. My relevant code is shown below, I am displaying the clock itself on a pygame window.

clocknum = clocknum + 0.05 # these 3 lines here are contained within a while loop for the rest of my game so constantly repeating
showclock(clocknum)
time.sleep(0.05)

def showclock(clocknum):
font = pygame.font.SysFont('bahnschrift', 20)
text = font.render(str(clocknum), 1, (0, 0, 0))
screen.blit(text, (5, 700))

Instead of going up in multiples of 5 like intended it is giving near but not quite accurate numbers such as :

3.349999999999999

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Basically the calculator is not entirely accurate and I’m wondering why, maybe due to the kind of data type im using? Just a simple integer , is there a better way to do this? All help appreciated

>Solution :

If you’re sleeping, and then also doing some computation, it’s never going to sleep exactly 0.05s, because there’s things that it needs to do in the meantime. I suggest you just round it to the nearest 2dp.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading