4 ms·
I notice that when you're trying to calculate whether a point (p) is in a circle (c) you use euclidean distance: Math.sqrt((p.x - c.x) ^ 2 + (p.y - c.y) ^ 2)
by shuzchen 11y ago
I notice that when you're trying to calculate whether a point (p) is in a circle (c) you use euclidean distance:
Math.sqrt((p.x - c.x) ^ 2 + (p.y - c.y) ^ 2) > c.radius
If you're doing this test many, many times (especially as in a Monte Carlo simulation), it'd be more efficient to use distanceSquared:
(p.x - c.x) ^ 2 + (p.y - c.y) ^ 2 > c.radius ^ 2
Not having to calculate square roots will cut the compute time drastically.
- benfrederickson 11y agogood point! I actually used this technique recently, to speed up a numerical optimization for laying out venn diagrams: http://www.benfrederickson.com/better-venn-diagrams/ http://www.benfrederickson.com/better-venn-diagrams/ I didn't think of it when I was writing this post though =(