w3resource

NumPy: Convert cartesian coordinates to polar coordinates

NumPy: Random Exercise-14 with Solution

Write a NumPy program to convert cartesian coordinates to polar coordinates of a random 10x2 matrix representing cartesian coordinates.

Sample Solution:

Python Code:

# Importing the NumPy library as np
import numpy as np

# Generating a random 10x2 array 'z' with random numbers between 0 and 1
z = np.random.random((10, 2))

# Extracting the first column as 'x' and the second column as 'y' from the array 'z'
x, y = z[:, 0], z[:, 1]

# Calculating the Euclidean distance (r) using the formula sqrt(x^2 + y^2)
r = np.sqrt(x**2 + y**2)

# Calculating the angles (t) using arctan2() function, which returns the arctangent of y/x in radians
t = np.arctan2(y, x)

# Displaying the calculated Euclidean distances (r)
print(r)

# Displaying the calculated angles (t) in radians
print(t)

Sample Output:

[ 0.46197382  0.07034582  0.89015703  1.06227375  1.29780158  0.32823362                                                                      
  0.99823096  0.74005334  0.38023205  0.62537423]                      
[ 1.05405564  1.09799508  0.75642993  0.97273388  0.86502465  0.88995172                                                                      
  0.3019899   1.05539822  0.91697477  1.22828465]

Explanation:

In the above exercise –

z = np.random.random((10, 2)): This line generates a 10x2 array of random float numbers between 0 and 1, representing the x and y coordinates of 10 points in 2D space.

x, y = z[:, 0], z[:, 1]: These lines separate the x and y coordinates of the points into two separate 1D arrays.

r = np.sqrt(x**2 + y**2): This line calculates the radius (distance from the origin) for each point using the Pythagorean theorem, i.e., r = sqrt(x^2 + y^2), where r is the radius, and x and y are the coordinates of the point.

t = np.arctan2(y, x): This line calculates the angle in radians for each point, measured counterclockwise from the positive x-axis, using the arctan2() function, which takes the y and x coordinates as arguments and returns the angle t in the range (-π, π].

Python-Numpy Code Editor:

Previous: Write a NumPy program to find the most frequent value in an array.
Next: Write a NumPy program to find the closest value (to a given scalar) in an array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.