在一个指定位置的圆内随机取若干个坐标点,num为数量,radius为圆的半径,(centerx, centery)为圆心坐标。
方法一:根据条件判断的随机点产生方法
import random
import matplotlib.pyplot as plt
def getRandomPointInCircle(num, radius, centerx, centery):
samplePoint = []
for i in range(num):
while True:
x = random.uniform(-radius, radius)
y = random.uniform(-radius, radius)
if (x ** 2) + (y ** 2) <= (radius ** 2):
samplePoint.append((int(x) + centerx, int(y) + centery))
break
plt.plot(x + centerx, y + centery, '*', color="blue")
return samplePoint
if __name__ == "__main__":
num = 1000
radius = 100
centerx,centery = 20, 20
samp = getRandomPointInCircle(num, radius, centerx, centery)
print("sample point" , samp)
plt.legend()
plt.show()
方法二:极坐标产生随机点
import random
import matplotlib.pyplot as plt
def getRandomPointInCircle(num, radius, centerx, centery):
samplePoint = []
for i in range(num):
theta = random.random() * 2 * np.pi
r = random.uniform(0, radius ** 2)
x = math.cos(theta) * (r ** 0.5) + centerx
y = math.sin(theta) * (r ** 0.5) + centery
samplePoint.append((int(x), int(y)))
plt.plot(x, y, '*', color="blue")
return samplePoint
if __name__ == "__main__":
num = 1000
radius = 100
centerx,centery = 20, 20
samp = getRandomPointInCircle(num, radius, centerx, centery)
print("sample point" , samp)
plt.legend()
plt.show()
显示效果
显示如下: