Fast next-after function in JavaScript

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.

+4
source share
2 answers

If your code is synchronous, you do not need to call new all the time, this means that you can save your Uint32Array and Float32Array , which are connected through the same buffer for all functions, for example

 var obj = (function () { var int = new Uint32Array(1), float = new Float32Array(int.buffer); return { i2f: function (i) { int[0] = i; return float[0]; }, f2i: function (f) { float[0] = f; return int[0]; }, next: function () { int[0] = int[0] + 1; return float[0]; }, prev: function () { int[0] = int[0] - 1; return float[0]; } }; }()); 
+3
source

Something like this should work and does not require array allocation:

 function testall(f) { var M = Math.pow(2,-126); var x; for (p = -1; p <= 1; p +=2) { for (s = 0; s < 1<<23; s++) { // subnormals (including zeros) x = p*M*(s/(1<<23)); f(x); } for (b = M; b <= 2/M; b *= 2) { for (s = 0; s < 1<<23; s++) { // normals x = p*b*(1+s/(1<<23)); f(x); } } } } 

This will lead to a repetition of all material floats (subnormals and normals). It will not handle Infs (there are only two of them, so I leave them to you) or NaNs (as far as I know, there is no effective way to repeat all NaN bit patterns in JavaScript).

+1
source

All Articles