如何在圆形区域内生成中心附近密度较高的随机点?

2024-04-25 09:06:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我们希望点越靠近中心,生成点的概率越高。因此,大多数点将围绕圆的中心聚集

到目前为止,我已经做了如下工作:

t = random.random() * 2 * math.pi
r = random.random() * radius
new_x = x_center + r * math.cos(t)
new_y = y_center + r * math.sin(t)

Tags: newpirandommathsincos概率中心
1条回答
网友
1楼 · 发布于 2024-04-25 09:06:17

您的算法已经在中心产生了更高的密度

您可以通过将random.random()提高到可变幂来影响密度,并使用它来定义r

例如,你可以这样做:

attraction = 3  # play with this value
t = random.random() * 2 * math.pi
r = random.random() ** attraction * radius  # < 
new_x = x_center + r * math.cos(t)
new_y = y_center + r * math.sin(t)

下面是一个JavaScript算法的交互式演示,您可以在其中使用附加参数并查看它给出了什么:

&13; 第13部分,;
let x_center = 80,
    y_center = 80,
    radius = 80;

function refresh(attraction=1) {
    clear();
    // Plot 10^4 random points in a disc
    for (let i = 0; i < 10000; i++) {
        let t = Math.random() * 2 * Math.PI
        let r = Math.random() ** attraction * radius
        let new_x = x_center + r * Math.cos(t)
        let new_y = y_center + r * Math.sin(t)
        plot(new_x, new_y);
    }
}


// I/O handling (would be different in Python)

let input = document.querySelector("input");
let canvas = document.querySelector("canvas");
let ctx = canvas.getContext("2d");

function plot(x, y) {
    ctx.beginPath();
    ctx.moveTo(x, y);
    ctx.lineTo(x + 0.5, y + 0.5);
    ctx.stroke();
}

function clear() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
}

input.addEventListener("input", () => refresh(input.value));
refresh(input.value);
input { width: 4em }
div { text-align: center }
<input type="number" value="1.0" step="0.1"><br>
<div><canvas width="160" height="160"></canvas></div>
和#13;
和#13;

相关问题 更多 >

    热门问题