javascript浮点数比较

时间:2012-09-24 13:46:29

标签: javascript floating-point

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

一个点是一个具有xy坐标以及b值的对象,存储它的亮度。

我的方法是设置一个p对象(可能性为p),其中startend值(均为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));
    }
};

输出:

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

- &GT; WTF? 0.56 < 0.53 < 0.67 ...

2 个答案:

答案 0 :(得分: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) {

operator precedence in javascript

答案 1 :(得分: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) 所以你可以正确地比较它们。

相关问题