# Addition not being performed correctly?

• 08-15-2012, 08:55 AM
Zwander
Addition not being performed correctly? <Solved- Floating point calculation errors>
First of all, hello, this is my first post on these forums. So uh, yea. Hi!

The below image demonstrates my problem. The green highlights show how the variables are set to the same values. The purple/blue shows the difference in resulting values, and the red shows the problem.

Attachment 4039

The number in red is the distance between the two objects. This should ALWAYS be "-1<dy>1" with dy being the distance.

Pretty much a[1] and b[1] are the objects y values. a[3] and b[3] is the dy values. ((y1+y1)-y2) (oops, its supposed to be +h1 not +y1. This is just visual though, the code is correct) is equal to the distance between the two objects.

a[1] and b[1] are added to a[3] and b[3] so that they move. The resulting difference in distance should be equal to -1. Especially seeing as I set a[1] and b[1] exactly 21 px apart, and subtracted the same numbers from them (see in green). If your wondering, both the green lines were run (there's a console entry a bit further up that proves it).

I'm sure this is due to something I have missed or miss spelt in my code, but I cant seem to find it.

If this is too confusing just say and I'll try to rephrase.

Thanks :D

Edit: Fixed some spelling.
• 08-15-2012, 09:22 AM
JosAH
Re: Addition not being performed correctly?
Read this article; it thoroughly explains the inaccuracies you get with floating point calculations; you have to live with it or come up with something smarter that reduces those numerical errors.

kind regards,

Jos
• 08-15-2012, 09:56 AM
Zwander
Re: Addition not being performed correctly?
Quote:

Originally Posted by JosAH
Read this article; it thoroughly explains the inaccuracies you get with floating point calculations; you have to live with it or come up with something smarter that reduces those numerical errors.

kind regards,

Jos

Ah, I see. I'm glad to see its not an error on my part.

Thing that intrigues me is that even when I rounded both sets of numbers the error still persisted. Not only that, but the error always occurs in the exacts same place despite the use off different numbers.

I guess I will resort to adding an approximation of the difference to the lacking number in order to fix this problem.