You are reading a single comment by @Gordon and its replies. Click here to read the full conversation.
  • Which board are you running this on?

    It looks like this is kind of a bug and kind of not a bug. What you're hitting is floating point inaccuracy.

    The issue boils down to whether this is true or false: 1-0.05 == 0.95

    You can't represent 0.05 or 0.95 exactly in a floating point number, so the nearest number is reported. So what you're doing is basically comparing 0.95 and 0.95000000001 (which just gets rounded in the console).

    In fact to show you the actual binary numbers behind o.95:

    >console.log(new Uint8Array(new Float64Array([0.95, 1-0.05]).buffer))
    new Uint8Array([
    103, 102, 102, 102, 102, 102, 238, 63, 
    102, 102, 102, 102, 102, 102, 238, 63])
    

    So there's one bit different in Espruino. I just checked with Node.js and it looks like the parsing of numbers is actually different, since Node.js gets 102, 102, 102, 102, 102, 102, 238, 63 for 0.95 as well but Espruino gets 103,...

    However it's really bad practice to do what you're doing anyway. Even if I fix this issue there will be cases where it fails. For instance the classic [0.3].indexOf(0.1+0.1+0.1) that used to trip up Windows Calculator still fails in Node.js (ironically it actually works in Espruino!).

    To work around this you could explicitly check if the number was close or not: tab1mAlpha.findIndex(a=>Math.abs(a-v)<0.000001)

    I think this kind of thing is always better to check on the forum with first - I have now filed a bug but in many cases they can be things that have been asked before - very often on GitHub I just keep getting similar issues filed time after time.

About

Avatar for Gordon @Gordon started