Skip to content

Commit 72d8feb

Browse files
committed
Add coordinate systems conversions (TheAlgorithms#2510)
1 parent 6a39545 commit 72d8feb

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

Diff for: maths/coordinate_conversion.py

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
""" Co-ordinate conversion """
2+
3+
from math import sin, cos, atan
4+
5+
def polar_to_cartesian(radius: float, angle: float) -> (float, float):
6+
"""
7+
This function returns (x, y) i.e. cartesian co ordinates
8+
given polar coordinates (r, theta)
9+
Reference:
10+
https://en.wikipedia.org/wiki/Polar_coordinate_system
11+
https://en.wikipedia.org/wiki/Cartesian_coordinate_system
12+
13+
>>> polar_to_cartesian(0, 0)
14+
(0.0, 0.0)
15+
>>> polar_to_cartesian(1, 0.7853981633974483)
16+
(0.7071067811865476, 0.7071067811865475)
17+
"""
18+
x_coordinate = radius * cos(angle)
19+
y_coordinate = radius * sin(angle)
20+
return (x_coordinate, y_coordinate)
21+
22+
def cartesian_to_polar(x_coordinate: float, y_coordinate : float) -> (float, float):
23+
"""
24+
This function returns (r, theta) i.e. cartesian co ordinates
25+
given polar coordinates (x, y)
26+
Reference:
27+
https://en.wikipedia.org/wiki/Polar_coordinate_system
28+
https://en.wikipedia.org/wiki/Cartesian_coordinate_system
29+
30+
>>> cartesian_to_polar(0, 0)
31+
(0.0, inf)
32+
>>> cartesian_to_polar(0.7071067811865476, 0.7071067811865475)
33+
(1.0, 0.7853981633974483)
34+
35+
"""
36+
radius = ((x_coordinate ** 2) + (y_coordinate ** 2)) ** 0.5 # root of x squared and y squared
37+
theta = atan( y_coordinate / x_coordinate ) if (x_coordinate != 0) else float("inf")
38+
return (radius, theta)
39+
40+
def main():
41+
import doctest
42+
doctest.testmod()
43+
44+
if __name__ == '__main__':
45+
main()

0 commit comments

Comments
 (0)