Adding random weighted point

☆樱花仙子☆ 提交于 2019-12-24 07:46:30

问题


Let's say I have a blank canvas with 2 red points in it.

Is there an algorithm to randomly add a point in the canvas but in a way where it's more bias to the red points with a supplied radius?

Here's a crude image as an example:

Even though this question is for Python it really applies for any language.


回答1:


Sure. Select first point or second point randomly, then generate some distribution with single scale parameter in polar coordinates, then shift by center point position. Select some reasonable radial distribution (gaussian in the code below, exponential or Cauchy might work as well)

import math
import random

import matplotlib.pyplot as plt

def select_point():
    p = random.random()
    if p < 0.5:
        return 0
    return 1

def sample_point(R):
    """
    Sample point inpolar coordinates
    """
    phi = 2.0 * math.pi * random.random() # angle
    r   = R * random.gauss(0.0, 1.0)      # might try different radial distribution, R*random.expovariate(1.0)

    return (r * math.cos(phi), r * math.sin(phi))

def sample(R, points):
    idx = select_point()

    x, y = sample_point(R)

    return (x + points[idx][0], y + points[idx][1])

R = 1.0
points = [(7.1, 3.3), (4.8, -1.4)]

random.seed(12345)

xx = []
yy = []
cc = []

xx.append(points[0][0])
xx.append(points[1][0])

yy.append(points[0][1])
yy.append(points[1][1])

cc.append(0.8)
cc.append(0.8)

for k in range(0, 50):
    x, y = sample(R, points)
    xx.append(x)
    yy.append(y)
    cc.append(0.3)

plt.scatter(xx, yy, c=cc)
plt.show()

Picture



来源:https://stackoverflow.com/questions/47265844/adding-random-weighted-point

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!