2

I need to generate 2D random coordinates and find the distance from one central location.

import numpy as np
import matplotlib.pyplot as plt

coords = np.random.random_integers(0,50,10)

print(coords)
Saleem Ali
  • 1,363
  • 11
  • 21
  • I tried to generate some random points by using the above code. But, I need to generate points in 2D and then calculate their distance from one (any) central point and store that distance value in the list. – Sheikh Salman Hassan Oct 31 '19 at 06:57
  • Use the size argument to generate a 2D output. Have a look here (https://numpy.org/devdocs/reference/random/generated/numpy.random.Generator.integers.html#numpy.random.Generator.integers) for the new Numpy Generator. The second example at the bottom of the page is what you are looking for. – Patol75 Oct 31 '19 at 07:09

2 Answers2

3

To sample coordinates you can also sample the x- and y-coordinates separately:

import numpy as np
import matplotlib.pyplot as plt

x = np.random.randint(0, 50, 10)
y = np.random.randint(0, 50, 10)

plt.scatter(x, y)
plt.show()

The output of the above should be a scatter plot with the 10 sampled points. Next you can determine the distance of all the points to a defined central point (x0, y0) as follows:

x0, y0 = 25, 25 
d = np.sqrt((x0 - x)**2 + (y0 - y)**2)
print(d)

Where d contains the distances to the central point and d[i] is the distance of (x[i], y[i]) to (x0, y0).

Wavy
  • 188
  • 7
1

There are some problems with your line of reasoning, moreover, your question is not very clear.

First, you need both coordinates for a point. At the moment you are creating only 10 random values. Are they x? y? Do you want only integer coordinates? I assumed that since you used a deprecated integer random value generator. In the answer you ask the distance from a central location, what do you mean exactly? Do you want the distance from each point to that location? An average? I tried to answer your question considering the central location as the centroid of the random points.

I generated 10 points.

I calculated the centroid with coordinate xm and ym.

In this case, to calculate the centroid you need just to compute the mean of your x coordinates and y coordinates.

If you want a specific location you just need to put numbers on xm and ym.

After I created a list "d1" where I can store the distance, for each point, to the centroid. The formula in the "for loop" is just the Euclidean distance.

import numpy as np
import matplotlib.pyplot as plt

num_points=10
coords_x=np.random.randint(0,50,num_points)
coords_y=np.random.randint(0,50,num_points)

xm=np.average(coords_x)
ym=np.average(coords_y)

d1=((coords_x-xm)**2+(coords_y-ym)**2)**0.5

print(d1)
Fabrizio
  • 927
  • 9
  • 20