Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A small optimization of Point/Circle #36

Open
martys71 opened this issue Aug 12, 2023 · 0 comments
Open

A small optimization of Point/Circle #36

martys71 opened this issue Aug 12, 2023 · 0 comments

Comments

@martys71
Copy link

You don't need to use sqrt here. Sqrt is expensive.

// POINT/CIRCLE
boolean pointCircle(float px, float py, float cx, float cy, float r) {

  // get distance between the point and circle's center
  // using the Pythagorean Theorem
  float distX = px - cx;
  float distY = py - cy;
  float distance = sqrt( (distX*distX) + (distY*distY) );

  // if the distance is less than the circle's
  // radius the point is inside!
  if (distance <= r) {
    return true;
  }
  return false;
}

You can just compare the squares easier and faster:
return distX*distX + distY*distY <= r*r;

(Thanks for the book!)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant