count += 1
x = x_center + (random.random() - 0.5) * length
y = y_center + (random.random() - 0.5) * width
print(x, y)
if __name__ == "__main__":
main(sys.argv)
# 调用方法:python test.py [x_center, y_center, length, width]
该序列位于某个圆形内【方法一:拒绝采样】
# test.py
import sys
import random
def main(argv):
x_center = float(argv[1])
y_center = float(argv[2])
radius = float(argv[3])
count = 0
while count < 10:
count += 1
x = x_center + (random.random() - 0.5) * radius * 2
y = y_center + (random.random() - 0.5) * radius * 2
if (x - x_center) ** 2 + (y - y_center) ** 2 <= radius ** 2:
print(x, y)
if __name__ == "__main__":
main(sys.argv)
# 调用方法:python test.py [x_center, y_center, radius]
该序列位于某个圆形内【方法二:极坐标】
# test.py
import sys
import math
import random
def main(argv):
x_center = float(argv[1])
y_center = float(argv[2])
radius = float(argv[3])
count = 0
while count < 10:
count += 1
theta = random.random() * 2 * math.pi
r = random.random() ** 0.5 * radius # 由于平面随机采样,所以需要开方,但是值域还是[0, 1]
x = x_center + r * math.cos(theta)
y = y_center + r * math.sin(theta)
print(x, y)
if __name__ == "__main__":
main(sys.argv)
# 调用方法:python test.py [x_center, y_center, radius]
随机点可视化
# -*- coding:utf-8 -*-
import sys
import numpy as np
import matplotlib.pyplot as plt
def main(argv):
x_center = float(argv[1])
y_center = float(argv[2])
radius = float(argv[3])
total = int(argv[4])
count = 0
x = np.zeros(total)
y = np.zeros(total)
while count < total:
theta = np.random.random() * 2 * np.pi
r = np.random.random() ** 0.5 * radius
x[count] = x_center + r * np.cos(theta)
y[count] = y_center + r * np.sin(theta)
print(x[count], y[count])
count += 1
plt.figure(figsize=(10,10.1),dpi=125)
# 画出各个点
plt.plot(x,y,'ro')
# 画出圆形
_t = np.arange(0,7,0.1)
_x = x_center + np.cos(_t) * radius
_y = y_center + np.sin(_t) * radius
plt.plot(_x,_y,'g-')
# 对坐标轴进行设置
plt.xlim(x_center - 1.1 * radius,x_center + 1.1 * radius)
plt.ylim(y_center - 1.1 * radius,y_center + 1.1 * radius)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Random Scatter')
plt.grid(True)
plt.savefig('imag.png')
plt.show()
if __name__=='__main__':
main(sys.argv)
终端调用python3 test.py 1 1 1 20
,生成位于圆心为(1,1),半径为1的圆形区域内的20个随机点,得到下图: