Skip to content

fix: wrong angle in cartesian_to_polar for Q4 and anti-diagonal points - #1609

Open
JayPokale wants to merge 1 commit into
TheAlgorithms:masterfrom
JayPokale:fix-cartesian-to-polar-angle
Open

JayPokale wants to merge 1 commit into
TheAlgorithms:masterfrom
JayPokale:fix-cartesian-to-polar-angle

Conversation

@JayPokale

Copy link
Copy Markdown

Description of Change

to_polar returned a wrong angle in two cases:

  • Fourth quadrant (x > 0, y < 0): atan(y / x) is already the right (negative) angle, but the code returned 2 * pi - atan(y / x). For (2, -1) it gave 6.7468 instead of -0.4636.
  • Second quadrant on the anti-diagonal (x == -y, x < 0): the Q1 condition || (x == -y) caught it, so (-1, 1) gave -pi/4 instead of 3pi/4.

Fix: drop the x == -y clause from the Q1 check and use *theta for Q4. Added test_quadrants(), which checks r and theta against hypot/atan2 for points in every quadrant, both diagonals and the axes.

Before: the file's own assertion fabs(theta - atan2(y, x)) < 0.01 already aborts on master here (Q4 points from rand), and the new test fails.
After: both test() and test_quadrants() pass, also with -fsanitize=address,undefined; clang-format is clean.

References

Fixes #1582

Checklist

  • Added description of change
  • Added file name matches File name guidelines
  • Added tests and example, test must pass
  • Relevant documentation/comments is changed or added
  • PR title follows semantic commit guidelines
  • Search previous suggestions before making a new one, as yours may be a duplicate.
  • I acknowledge that all my contributions will be made under the project's license.

Notes: Fixes the wrong angle for Q4 and anti-diagonal inputs in to_polar.

This branch has not been deployed

No deployments
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

Successfully merging this pull request may close these issues.

math/cartesian_to_polar: to_polar returns wrong angle for fourth-quadrant points (x>0, y<0)

1 participant