Python Complete the function below distance_from_origin(points) that calculates
ID: 3598337 • Letter: P
Question
Python
Complete the function below distance_from_origin(points) that calculates the distance from the origin for a numpy array of points whose shape is (n, 2) where n is any arbitrary number of points. Return a numpy array of distances where each element in the array corresponds to the distance from the origin for the respective point in the points array. Reminder that the distance for a point (x1,y1)(x1,y1) from the origin can be defined as: d=((x1)^2+(y1)^2). For example if points = [[2, 2], [3, 2]], then the resulting distance array would be [2.828427, 3.605551]. This is because applying the distance formula on [2, 2] would result in 88 which is approximately 2.828427, and similarly for [3, 2], the distance would be 1313 which is approximately 3.605551. Set result equal to the return value and return result.
def distance_from_origin(points):
%matplotlib inline
# plotting tools
import numpy as np
from scipy.spatial.distance import cdist
import matplotlib.pyplot as plt
from nose.tools import assert_equal, assert_true, assert_almost_equal
from numpy.testing import assert_array_almost_equal
"""
Returns an array of distances from the origin for all points.
Parameters
----------
points: numpy array of float64
Returns
-------
numpy.array of float64
"""
result = None
# YOUR CODE HERE
return result
Explanation / Answer
Here is the code for you:
#!/usr/bin/python
def distance_from_origin(points):
%matplotlib inline
# plotting tools
import numpy as np
from scipy.spatial.distance import cdist
import matplotlib.pyplot as plt
from nose.tools import assert_equal, assert_true, assert_almost_equal
from numpy.testing import assert_array_almost_equal
"""
Returns an array of distances from the origin for all points.
Parameters
----------
points: numpy array of float64
Returns
-------
numpy.array of float64
"""
result = None
# YOUR CODE HERE
result = []
import math
for i in range(len(points)):
distance = math.sqrt(points[i][0] * points[i][0] + points[i][1] * points[i][1])
result.append(distance)
return result
print distance_from_origin([[2, 2], [3, 2]])
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.