javascript浮点数比较

Pet*_*ter 2 javascript floating-point

我尝试做某种"随机发生器" - 有几个相邻的点,根据它们的亮度,它们或多或少可能被选中.

的点是与对象xy坐标和一个b值,存储它的亮度.

我的方法是设置一个p对象(p可能性),它有一个start和一个end值(都在0和1之间) - 值startend值之间的差异取决于它们的亮度.

然后我生成一个随机数并遍历所有点以查看随机数是否在它们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));
    }
};
Run Code Online (Sandbox Code Playgroud)

输出:

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
Run Code Online (Sandbox Code Playgroud)

- > WTF?0.56 < 0.53 < 0.67??

Den*_*ret 5

你要

if (curr_point.p.start < rand  && rand < curr_point.p.end) {
Run Code Online (Sandbox Code Playgroud)

代替

if (curr_point.p.start < rand < curr_point.p.end) {
Run Code Online (Sandbox Code Playgroud)

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

if ((curr_point.p.start < rand) < curr_point.p.end) {
Run Code Online (Sandbox Code Playgroud)

并且当在这样的操作中使用时,布尔值被转换为1或0,您正在测试

if (0 < 0.67) {
Run Code Online (Sandbox Code Playgroud)

javascript中的运算符优先级