Skip to content

Instantly share code, notes, and snippets.

@adnils
Created January 30, 2014 10:05
Show Gist options
  • Save adnils/8705644 to your computer and use it in GitHub Desktop.
Save adnils/8705644 to your computer and use it in GitHub Desktop.
find the next representable double float
"use strict";
var SMALLEST_NORMALIZED_VALUE = 2.2250738585072014e-308; // Math.pow(2, -1022)
var MIN_VALUE = 5e-324 === 0 ? SMALLEST_NORMALIZED_VALUE : 5e-324;
var MAX_VALUE = Number.MAX_VALUE;
Math.nextUp = function (x) {
x = Number(x);
if (x !== x) {
return x;
}
if (x === -Infinity) {
return -MAX_VALUE;
}
if (x === +Infinity) {
return +Infinity;
}
if (x === MAX_VALUE) {
return +Infinity;
}
var a = x;
var d = (x < 0 ? -x : x) * 0.0000000000000002;
if (d < MIN_VALUE) {
d = MIN_VALUE;
}
var b = x + d;
if (b === +Infinity) {
b = MAX_VALUE;
}
var m = x;
while (b !== a) {
var c = (b + a) / 2;
if (c === -Infinity || c === Infinity) {
c = a + (b - a) / 2;
}
if (m === c) {
return b === 0 && x < 0 ? -0 : b;
}
m = c;
if (x < m) {
b = m;
} else {
a = m;
}
}
return b === 0 && x < 0 ? -0 : b;
};
Math.nextAfter = function (x, y) {
x = Number(x);
y = Number(y);
if (y < x) {
return -Math.nextUp(-x);
}
if (x < y) {
return Math.nextUp(x);
}
return x !== x || y !== y ? NaN : y;
};
if (false && Float64Array && Uint16Array) {
var float64Array = new Float64Array(1);
var uint16Array = new Uint16Array(float64Array.buffer);
Math.nextUp = function (x) {
x = Number(x);
if (x !== x) {
return NaN;
}
if (x === +Infinity) {
return x;
}
if (x === 0) {
return MIN_VALUE;
}
float64Array[0] = x;
var n = x < 0 ? -1 : 1;
var i = -1;
while (n !== 0) {
++i;
n += uint16Array[i];
uint16Array[i] = n & 0xffff;
n >>= 16;
}
return float64Array[0];
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment