简体   繁体   中英

Random 2D coordinates generation

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)

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) .

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM