【发布时间】:2020-04-24 05:29:13
【问题描述】:
在 python 中,如何生成位于半径为 r 的圆内的随机点对 (x,y)。
基本上x和y应该满足条件x^2 + y^2 = r^2。
【问题讨论】:
-
问题含糊不清 -
inside a circle of radius r假设 x^2 + y^2 r^2.
标签: python-3.x numpy random geometry coordinates
在 python 中,如何生成位于半径为 r 的圆内的随机点对 (x,y)。
基本上x和y应该满足条件x^2 + y^2 = r^2。
【问题讨论】:
inside a circle of radius r 假设 x^2 + y^2 r^2.
标签: python-3.x numpy random geometry coordinates
要在半径为r的原点圆内生成均匀分布的点,可以在0..1范围内生成两个均匀值t,u并使用the next formula:
import math, random
r = 4
t = random.random()
u = random.random()
x = r * math.sqrt(t) * math.cos(2 * math.pi * u)
y = r * math.sqrt(t) * math.sin(2 * math.pi * u)
print (x,y)
【讨论】:
t 应该在Uniform[r1**2/r2**2, 1] 范围内
使用 numpy 一次生成多个点:
import numpy as np
import matplotlib.pyplot as plt
n_samples = 1000
r = 4
# make a simple unit circle
theta = np.linspace(0, 2*np.pi, n_samples)
a, b = r * np.cos(theta), r * np.sin(theta)
t = np.random.uniform(0, 1, size=n_samples)
u = np.random.uniform(0, 1, size=n_samples)
x = r*np.sqrt(t) * np.cos(2*np.pi*u)
y = r*np.sqrt(t) * np.sin(2*np.pi*u)
# Plotting
plt.figure(figsize=(7,7))
plt.plot(a, b, linestyle='-', linewidth=2, label='Circle', color='red')
plt.scatter(x, y, marker='o', label='Samples')
plt.ylim([-r*1.5,r*1.5])
plt.xlim([-r*1.5,r*1.5])
plt.grid()
plt.legend(loc='upper right')
plt.show(block=True)
导致:
【讨论】: