2

我试图做某种“随机发生器”——有几个相邻的点,根据它们的亮度,它们或多或少有可能被选中。

一个点是一个具有坐标和x值的对象,存储它的亮度。yb

我的方法是设置一个具有 a和一个值(介于 0 和 1 之间)的p对象(用于可能性) -和值之间的差异取决于它们的亮度。pstartendstartend

然后我生成一个随机数并遍历所有点以查看随机数是否在它们startend属性之间。由于一个点start值是前一个点的end值,因此只应选择一个点,而是选择随机数量的点。

因此,我记录了随机值以及点startend属性。看起来一切正常,除了以下代码

for (i = 0; i < numAdjacentPoints; i++) {
    // set some shorthands
    curr_point = adjacentPoints[i];
    // if there is no previous point, we start with 0
    prev_point = ((i === 0) ? {p: {end: 0}} : adjacentPoints[i-1]);
    // initiate a probability object
    curr_point.p = {};
    // set a start value (the start value is the previous point's end value)
    curr_point.p.start = prev_point.p.end;
    // set an end value (the start value + the point's brightness' share of totalBrightness)
    // -> points with higher darkness (255-b) are more have a higher share -> higher probability to get grown on
    curr_point.p.end   = curr_point.p.start + (255 - curr_point.b) / totalBrightness;
    // if the random value is between the current point's p values, it gets grown on
    if (curr_point.p.start < rand < curr_point.p.end) {
        // add the new point to the path array
        path[path.length] = curr_point;
        // set the point's brightness to white -> it won't come into range any more
        curr_point.b = 255;
        console.log("  we've got a winner! new point is at "+curr_point.x+":"+curr_point.y);
        console.log("  "+curr_point.p.start.toFixed(2)+" < "+rand.toFixed(2)+" < "+curr_point.p.end.toFixed(2));
    }
};

输出这个:

we've got a winner! new point is at 300:132 mycelium.php:269
0.56 < 0.53 < 0.67 mycelium.php:270
we've got a winner! new point is at 301:130 mycelium.php:269
0.67 < 0.53 < 0.78 mycelium.php:270
we've got a winner! new point is at 301:131 mycelium.php:269
0.78 < 0.53 < 0.89 mycelium.php:270
we've got a winner! new point is at 301:132 mycelium.php:269
0.89 < 0.53 < 1.00

--> 怎么回事?0.56 < 0.53 < 0.67??

4

2 回答 2

5

你要

if (curr_point.p.start < rand  && rand < curr_point.p.end) {

代替

if (curr_point.p.start < rand < curr_point.p.end) {

您正在将数字与比较结果进行比较,即布尔值。您的代码相当于

if ((curr_point.p.start < rand) < curr_point.p.end) {

并且当在此类操作中使用布尔值时,它会转换为 1 或 0,因此您正在测试

if (0 < 0.67) {

javascript中的运算符优先级

于 2012-09-24T13:48:08.250 回答
1

你不可以做这个:

if (curr_point.p.start < rand < curr_point.p.end)

因为curr_point.p.start < rand将被评估为一个boolean然后,你会有一些你不想要的东西: if (boolean < curr_point.p.end)

正确的条件是这样的:

if (curr_point.p.start < rand  && rand < curr_point.p.end)

在这种情况下,您将有两个布尔值: if (boolean1 && boolean2) 因此您可以正确比较它们。

于 2012-09-24T14:01:22.553 回答