The other day it occurred to me an intuitive way to test if a point is inside a triangle.
(Assume all numbers floating points of some kind)
The euclidean distance is relatively expensive, because it uses square root. We can alleviate that by squaring all our distances instead.
- Code: Select all
let dist(P1, P2) = x * x + y * y
where x = P1.x - P2.x
y = P1.y - P2.y
Three additions, two multiplications.
When we look at a triangle, all the points inside the triangle have distances to the corners shorter than or equal to the sides.
- Code: Select all
let inside(P, A, B, C) = pa < ab && pa < ca && pb < ab && pb < bc && pc < bc && pc < ca
where pa = dist(P, A)
pb = dist(P, B)
pc = dist(P, C)
ab = dist(A, B)
bc = dist(B, C)
ca = dist(C, A)
Six floating comparisons, five boolean conjunctions, six uses of dist (18 additions, 12 multiplications).
This algorithm just occurred to me. I know this is probably reinventing the wheel, but hey, it's my hobby.
Most of the approaches I see are to use vector operations which I can see makes sense in 3d and when you have a GPU handy. What if you don't?
Do you ever discover or "play" with algorithms?
What novel approaches have you encountered?
Got any gems to share?
