繁体   English   中英

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

[英]How to generate random points within a circular area, with higher density near the center?

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

到目前为止,我已经做了这样的事情:

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)

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

您可以通过将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 中算法的交互式演示,您可以在其中使用附加参数并查看它给出的结果:

 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM