本文介绍了在Python中生成一条线上方和下方的随机点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在给定线上方或下方的 x,y 散点图上生成随机点.例如,如果线是 y=x,我想在图的左上角(线上方)生成一个点列表,并在图的右下角(线下方)生成一个点列表.以下是点高于或低于 y=5 的示例:

I would like to generate random points on an x,y scatter plot that are either above or below a given line. For example, if the line is y=x I would like to generate a list of points in the top left of the plot (above the line) and a list of points in the bottom right of the plot (below the line). Here's is an example where the points are above or below y=5:

import random
import matplotlib.pyplot as plt

num_points = 10
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=1, stop=5) for i in range(num_points)]
y2 = [random.randrange(start=6, stop=9) for i in range(num_points)]

plt.scatter(x1, y1, c='blue')
plt.scatter(x2, y2, c='red')
plt.show()

但是,我独立生成了 x 和 y 点,这将我限制为 y = c(其中 c 是常数)的方程.如何将其扩展到任何 y=mx+b?

However, I generated the x and y points independently, which limits me to equations where y = c (where c is a constant). How can I expand this to any y=mx+b?

推荐答案

您可以将 y1y2 的停止和开始限制更改为您想要的行.您需要决定平面的终点(设置 lowerupper).

You can change the stop and start limits for y1 and y2 to be the line you want. You will need to decide where the plane ends (set lower and upper).

注意这仅适用于整数.如果您想要更复杂的东西,您可以使用截断的多元分布.

Note this only works for integers. You can use truncated multivariate distributions if you want something more sophisticated.

m, b = 1, 0
lower, upper = -25, 25

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=m*x+b) for x in x1]
y2 = [random.randrange(start=m*x+b, stop=upper) for x in x2]

plt.plot(np.arange(10), m*np.arange(10)+b)
plt.scatter(x1, y1, c='blue')
plt.scatter(x2, y2, c='red')

这篇关于在Python中生成一条线上方和下方的随机点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 01:13