Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialLuis Marsano
21,425 PointsUnsound mathematics could result in bugs
The presenter says
We're only using whole numbers in our game. An invader can't be halfway between two grid squares. Truncating the decimal value we get from this formula gives us the correct distance in discrete units.
This has a number of problems.
- A non-integer distance doesn't mean "halfway between two grid squares". It means some distances simply aren't integers. Even though (0, 0) and (1, 1) are not "halfway between two grid squares", the distance from (0, 0) to (1, 1) is √2.
-
That truncation gives a 'correct distance in discrete units' is asserted without proof. It's actually untrue: distance with truncation is no longer a valid distance function. Consider the collinear points
p0=(0, 0)
,p1=(1, 1)
,p2=(3, 3)
.-
We should be able to breakdown distances and have
d(p0, p2) = d(p0, p1) + d(p1, p2)
right? Not with truncation:
⌊d(p0, p1)⌋ = 1 ⌊d(p1, p2)⌋ = 2 ⌊d(p0, p2)⌋ = 4 ≠ 1 + 2 = ⌊d(p0, p1)⌋ + ⌊d(p1, p2)⌋
-
It's even worse: a distance function
d
should satisfy the triangle inequality:d(p0, p2) ≤ d(p0, p1) + d(p1, p2)
However,
⌊d⌋
does not⌊d(p0, p1)⌋ + ⌊d(p1, p2)⌋ = 3 < 4 = ⌊d(p0, p2)⌋
-
Our game will run into problems if we ever need to add "distances" or compare sums of "distances".
A better alternative for working with integers might be to skip sqrt
and work in terms of squared distances.
1 Answer
Milosz Drozd
9,500 PointsHi Luis! This reasoning is very sensible to me. Would anyone like to elaborate on that ?