UNPKG

diffusion

Version:

Diffusion JavaScript client

94 lines (93 loc) 2.61 kB
"use strict"; /** * @module Util.Math * * @brief Mathenatical utility functions */ /* eslint-disable no-bitwise */ Object.defineProperty(exports, "__esModule", { value: true }); exports.MIN_SAFE_INTEGER = exports.MAX_SAFE_INTEGER = exports.MAX_INT32 = exports.findNextPowerOfTwo = exports.approximateSquareRoot = void 0; var errors_1 = require("./../../errors/errors"); /** * Calculate the number of leading zeros in the binary representation of a number * using the minimal amount of bit-shifting * * @param i the number to analyse * @return the number of leading binary zeros */ function leadingZeros(i) { if (i === 0) { return 32; } var n = 1; if (i >>> 16 === 0) { n += 16; i <<= 16; } if (i >>> 24 === 0) { n += 8; i <<= 8; } if (i >>> 28 === 0) { n += 4; i <<= 4; } if (i >>> 30 === 0) { n += 2; i <<= 2; } n -= i >>> 31; return n; } /** * Cheap approximation to a square root. * * @param value the argument of the square-root function * @return a power of two that approximates the square root of a value * @throws an {@link IllegalArgumentError} if the value is negative */ function approximateSquareRoot(value) { if (value < 0) { throw new errors_1.IllegalArgumentError('Value must be great or equal to 0'); } if (value === 0) { return 0; } var h = 32 - leadingZeros(value); return 1 << Math.round(h / 2); } exports.approximateSquareRoot = approximateSquareRoot; /** * Find the next integer, equal or higher to the value, which is a power of two. * * @param value the value to search from * @returns the next power of two * @throws an {@link IllegalArgumentError} if the value is negative or greater than 2^30 */ function findNextPowerOfTwo(value) { if (value < 0 || value > 1 << 30) { throw new errors_1.IllegalArgumentError('Illegal argument: ' + value); } // see: https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 value--; value |= value >> 1; value |= value >> 2; value |= value >> 4; value |= value >> 8; value |= value >> 16; value++; return value; } exports.findNextPowerOfTwo = findNextPowerOfTwo; /** * Maximum 32 bit integer value: 2^32 - 1 */ exports.MAX_INT32 = 2147483647; /** * Maximum safe integer value for JavaScript numbers: 2^53 - 1 */ exports.MAX_SAFE_INTEGER = 9007199254740991; /** * Minimum safe integer value for JavaScript numbers: -(2^53 - 1) */ exports.MIN_SAFE_INTEGER = -9007199254740991;