首页 > 解决方案 > 在由 numpy 数组 python 创建的行的下方和上方生成随机浮点数

问题描述

我想在由 numpy 数组创建的线的上方和下方生成一个随机浮点数。

例如,我有这些线方程:

x_values = np.linspace(-1, 1, 100)

y1 = 2 * x_values -5
y2= -3 * x_values +2

plt.plot(x_values,y1, '-k')
plt.plot(x_values,y2, '-g')

我已经从在 Python 中的一行上方和下方生成随机点尝试了这种方法,如果np.arrange像这样使用它,它就可以工作:

lower, upper = -25, 25

num_points = 1
x1 = [random.randrange(start=1, stop=9) for i in range(num_points)]
x2 = [random.randrange(start=1, stop=9) for i in range(num_points)]

y1 = [random.randrange(start=lower, stop=(2 * x -5) )for x in x1]
y2 = [random.randrange(start=(2 * x -5), stop=upper) for x in x2]

plt.plot(np.arange(10), 2 * np.arange(10) -5)
plt.scatter(x1, y1, c='blue')
plt.scatter(x2, y2, c='red')

np.linspace(-1, 1, 100)但是,如果用于创建折线图,我想找到一种生成随机点的方法。不同之处在于涉及/允许选择浮动坐标。但不确定如何。

任何想法将不胜感激。

标签: pythonmatplotlib

解决方案


这是一种方法,使用 y 值的函数。在 x 范围内均匀选择随机 x 位置。对于每个随机 x,在其 y 范围之间随机选择一个值。

import numpy as np
import matplotlib.pyplot as plt

x_values = np.linspace(-1, 1, 100)
f1 = lambda x: 2 * x - 5
f2 = lambda x: -3 * x + 2

y1 = f1(x_values)
y2 = f2(x_values)

plt.plot(x_values, y1, '-k')
plt.plot(x_values, y2, '-g')
plt.fill_between (x_values, y1, y2, color='gold', alpha=0.2)

num_points = 20
xs = np.random.uniform(x_values[0], x_values[-1], num_points)
ys = np.random.uniform(f1(xs), f2(xs))
plt.scatter(xs, ys, color='crimson')

plt.show()

示例图

PS:请注意,该方法的简单性在其长度上选择 x 统一。如果您需要在梯形区域上均匀分布,则需要右边的 x 概率较小,左边的概率更大。您可以使用更多点并使用透明度来可视化这一点。使用简单的方法,右侧看起来比左侧更密集。

以下代码首先在平行四边形中生成 x,y 点,并将错误一侧的点重新映射回其镜像位置。代码如下所示:

import numpy as np
import matplotlib.pyplot as plt

x0, x1 = -1, 1
x_values = np.linspace(x0, x1, 100)
f1 = lambda x: 2 * x - 5
f2 = lambda x: -3 * x + 2

y1 = f1(x_values)
y2 = f2(x_values)
plt.plot(x_values, y1, '-k')
plt.plot(x_values, y2, '-g')
plt.fill_between(x_values, y1, y2, color='gold', alpha=0.2)

num_points = 100_000
h0 = f2(x0) - f1(x0)
h1 = f2(x1) - f1(x1)
xs1 = np.random.uniform(x0, x1, num_points)
ys1 = np.random.uniform(0, h0 + h1, num_points) + f1(xs1)
xs = np.where(ys1 <= f2(xs1), xs1, x0 + x1 - xs1)
ys = np.where(ys1 <= f2(xs1), ys1, f1(xs) + h0 + h1 + f1(xs1) - ys1)
plt.scatter(xs, ys, color='crimson', alpha=0.2, ec='none', s=1)
plt.show()

绘制比较两种方法的图:

比较图


推荐阅读