我正在嘗試做一個簡單的「人羣」模型,並需要在二維區域內分佈隨機點。這個半僞代碼是我最好的嘗試,但即使在我運行它之前,我也可以看到大問題,對於密集人羣來說,新點過於接近的機會可能會非常快地變得非常高,使得它非常低效並且容易失敗,除非這些值被微調。可能與已簽名的值有關,但爲了簡單起見,我將其留下。在2D中分配隨機點
int numPoints = 100;
int x[numPoints];
int y[numPoints];
int testX, testY;
tooCloseRadius = 20;
maxPointChecks = 100;
pointCheckCount = 0;
for (int newPoint = 0; newPoint < numPoints; newPoint++){
//Keep checking random points until one is found with no other points in close proximity, or maxPointChecks reached.
while (pointCheckCount < maxPointChecks){
tooClose = false;
// Make a new random point and check against all previous points
testX = random(1000);
testY = random(1000);
for (testPoint = 0; testPoint < newPoint; testPoint++){
if ((isTooClose (x[testPoint] , y[testPoint], textX, testY, tooCloseRadius)) {
tooClose = true;
break; // (exit for loop)
}
if (tooClose == false){
// Yay found a point with some space!
x[newPoint] = testX;
y[newPoint] = testY;
break; // (exit do loop)
}
//Too close to one of the points, start over.
pointCheckCount++;
}
if (tooClose){
// maxPointChecks reached without finding a point that has some space.
// FAILURE DEPARTMENT
} else {
// SUCCESS
}
}
// Simple Trig to check if a point lies within a circle.
(bool) isTooClose(centerX, centerY, testX, testY, testRadius){
return (testX - centreX)^2 + (testY - centreY)^2) < testRadius ^2
}
谷歌搜索的主題後,我相信我做了什麼叫做拒絕採樣(?),以及自適應拒絕抽樣可能是一個更好的辦法,但數學是過於複雜。
是否有任何優雅的方法來實現這一點,不需要統計學學位?
您能解釋uniform_random嗎?這是從0->範圍的標準隨機函數嗎? – Kez
@凱茲是的。它將在[0,upper_bound]範圍內返回一致的數值概率,其中upper_bound是最大邊的長度。 –
好的,但爲什麼使用range而不只是x = uniform_random(0,rect_width);等等? – Kez