在三角域内生成随机位置 [英] Generate random locations within a triangular domain

查看:58
本文介绍了在三角域内生成随机位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成 xy 具有均匀分布并受 [xmin,xmax][ymin,ymax]

I want to generate x and y having a uniform distribution and limited by [xmin,xmax] and [ymin,ymax]

点 (x,y) 应该在三角形内.

The points (x,y) should be inside a triangle.

我该如何解决这样的问题?

How can I solve such a problem?

推荐答案

这里有一些代码可以在平面上的任意三角形上均匀地生成点.

Here's some code that generates points uniformly on an arbitrary triangle in the plane.

import random

def point_on_triangle(pt1, pt2, pt3):
    """
    Random point on the triangle with vertices pt1, pt2 and pt3.
    """
    s, t = sorted([random.random(), random.random()])
    return (s * pt1[0] + (t-s)*pt2[0] + (1-t)*pt3[0],
            s * pt1[1] + (t-s)*pt2[1] + (1-t)*pt3[1])

这个想法是计算三个顶点的加权平均值,权重由单位间隔 [0, 1] 的随机中断给出三部分(均匀地在所有这些中断上).

The idea is to compute a weighted average of the three vertices, with the weights given by a random break of the unit interval [0, 1] into three pieces (uniformly over all such breaks).

以下是在三角形中生成 10000 个点的示例用法:

Here's an example usage that generates 10000 points in a triangle:

pt1 = (1, 1)
pt2 = (2, 4)
pt3 = (5, 2)
points = [point_on_triangle(pt1, pt2, pt3) for _ in range(10000)]

以及从上面获得的图,证明了均匀性.该图由以下代码生成:

And a plot obtained from the above, demonstrating the uniformity. The plot was generated by this code:

import matplotlib.pyplot as plt
x, y = zip(*points)
plt.scatter(x, y, s=0.1)
plt.show()

图片如下:

并且由于您使用numpy"标签标记了问题,因此这里有一个 NumPy 版本,可以一次生成多个样本.请注意,它使用矩阵乘法运算符 @,在 Python 3.5 中引入并在 NumPy >= 1.10 中支持.您需要在较旧的 Python 或 NumPy 版本上将其替换为对 np.dot 的调用.

And since you tagged the question with the "numpy" tag, here's a NumPy version that generates multiple samples at once. Note that it uses the matrix multiplication operator @, introduced in Python 3.5 and supported in NumPy >= 1.10. You'll need to replace that with a call to np.dot on older Python or NumPy versions.

import numpy as np

def points_on_triangle(v, n):
    """
    Give n random points uniformly on a triangle.

    The vertices of the triangle are given by the shape
    (2, 3) array *v*: one vertex per row.
    """
    x = np.sort(np.random.rand(2, n), axis=0)
    return np.column_stack([x[0], x[1]-x[0], 1.0-x[1]]) @ v


# Example usage
v = np.array([(1, 1), (2, 4), (5, 2)])
points = points_on_triangle(v, 10000)

这篇关于在三角域内生成随机位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆