【问题标题】:Random function in python to generate random pair inside a circlepython中的随机函数在圆内生成随机对
【发布时间】: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


【解决方案1】:

要在半径为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)

【讨论】:

  • 可以进行哪些更改以使 x 和 y 位于半径为 r1 和 r2 的两个同心圆的区域之间。 r1^2
  • @MBo 我认为t 应该在Uniform[r1**2/r2**2, 1] 范围内
  • 对于环 - 使用 RandomUniform 在 (r1/r2)**2..1 范围内生成值 t 并使用 x = r2 * math.sqrt(t)...Corresponding answer
【解决方案2】:

使用 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)

导致:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-13
    • 2021-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多