生成一组 n = 100 X = {xi}, i = 1,...n, xi ∈ Python 中椭圆内的 R^2



完整的问题是生成一组 n = 100 点,X = {xi},i = 1,...n, xi ∈ R^2 在一个椭圆 (x − μx)^2/a^2 + (y − μy)^2/b^2 以 [μx, μy] = [5, −5] 为中心,长轴 2a = 10,短轴 2b = 5 散点图显示 Python 中的所有点。我被困在一个问题上。如何在椭圆内绘制 n = 100 个点?

您可以使用椭圆的参数方程:

import matplotlib.pyplot as plt
import numpy as np
xm, ym = 5, -5
a, b = 5, 2.5
f, ax = plt.subplots()
# Draw an ellipse centered at xm, ym.
# Use parametric equation of an ellipse.
# t is the angle
t = np.linspace(0, 2*np.pi)
ax.plot(a * np.cos(t) + xm, b * np.sin(t) + ym)
# Generate N random points inside the ellipse
N = 100
# N random points along the angle
tr = np.random.random(N) * 2 * np.pi
# N random points along the semi major axis
ar = a * np.random.random(N)
# N random points along the semi minor axis
br = b * np.random.random(N)
xr = ar * np.cos(tr) + xm
yr = br * np.sin(tr) + ym
ax.plot(xr, yr, linestyle="none", marker=".")
ax.set_aspect("equal")
plt.show()

最新更新