math - 加权随机坐标

标签 math random weighted

这可能更多的是搜索术语,但也欢迎提供解决方案。我正在寻找创建 n 个随机 x,y 坐标。我遇到的问题是我希望坐标被“加权”或者有更多的机会接近特定点。我使用以下伪代码创建了一些接近的东西:

x = rand(100) //random integer between 0 and 100
x = rand(x) //random number between 0 and the previous rand value
//randomize x to positive or negative
//repeat for y

这可以将对象拉向 0,0 - 但是如果您创建足够的点,您可以看到 x 和 y 轴的图案。这是因为即使 x 设法达到 100,y 也很可能更接近。

我希望避免形成这条 x,y 线。如果有一种方法可以放入多个“加权坐标”,随机坐标会倾向于该坐标,而不是静态地指向 0,0,那就加分了。

最佳答案

这在极坐标中更容易。您所要做的就是生成均匀的随机角度和功率分布距离。下面是一个 Python 示例:

import math
from random import random

def randomPoint(aroundX, aroundY, scale, density):
  angle = random()*2*math.pi

  x = random()
  if x == 0:
    x = 0.0000001

  distance = scale * (pow(x, -1.0/density) - 1)
  return (aroundX + distance * math.sin(angle),
          aroundY + distance * math.cos(angle))

这是randomPoint(0, 0, 1, 1)的分布:

Points spread out, more dense at the origin

我们可以使用 randomPoint(1, 2, 1, 1) 将其移动到围绕另一个点(如 1,2)的中心:

Points spread out, more dense at the 1,2

我们可以通过扩大规模来扩展到更大的区域。这是randomPoint(0, 0, 3, 1):

Points spread out randomly over a larger area

我们可以通过改变密度来改变形状,即聚集在一起的趋势。 随机点(0, 0, 1, 3):

Points tightly centered around the origin

关于math - 加权随机坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23700822/

相关文章:

c++ - 整合功能

scala - 在 Scala 中生成文件名的功能方法

r - dplyr中多列的加权平均值

c - 找到所有 m 子序列的最大加权和

Java 求两个整数的中点

math - 找到两个整数的最大同余模?

javascript - 从一组数字中计算百分比

ios - 随机给 Sprite 着色,但需要限制

vb.net - 需要生成 9 个小于 100 的唯一整数,使得没有两个整数的总和等于另外一/两个数字

r - R 中的 "weighted"回归