I am trying to iterate through all 32-bit floating point numbers in JavaScript to visually compare some methods for polynomial precision estimation. To do this, I implemented the code shown below. Unfortunately, this code is too slow.
Will there be any way to improve performance?
In C / C ++, the equivalent code runs a little over a minute on my computer, while I did not have the patience to see how long this code takes.
function nextFloat(f) { // Note that this moves away from 0.0 // It will fail at +/- infinity and result in an NaN var bitRepr = floatToBits(f); bitRepr++; return bitsToFloat(bitRepr); } function prevFloat(f) { // Note that this moves towards 0.0 // This will fail at 0.0 and result in an NaN var bitRepr = floatToBits(f); bitRepr--; return bitsToFloat(bitRepr); } function floatToBits(f) { var buf = new ArrayBuffer(4); (new Float32Array(buf))[0] = f; return (new Uint32Array(buf))[0]; } function bitsToFloat(b) { var buf = new ArrayBuffer(4); (new Uint32Array(buf))[0] = b; return (new Float32Array(buf))[0]; }
Another method I can consider is to use multiplying the number by (1 + epsilon), although I believe that it has extreme cases that I still have to solve at the bit level.
source share