normalize.js (2188B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var FLOAT64_SMALLEST_NORMAL = require( '@stdlib/constants/float64/smallest-normal' ); 24 var isInfinite = require( '@stdlib/math/base/assert/is-infinite' ); 25 var isnan = require( '@stdlib/math/base/assert/is-nan' ); 26 var abs = require( '@stdlib/math/base/special/abs' ); 27 28 29 // VARIABLES // 30 31 // (1<<52) 32 var SCALAR = 4503599627370496; 33 34 35 // MAIN // 36 37 /** 38 * Returns a normal number `y` and exponent `exp` satisfying \\(x = y \cdot 2^\mathrm{exp}\\). 39 * 40 * @private 41 * @param {(Array|TypedArray|Object)} out - output array 42 * @param {number} x - input value 43 * @returns {(Array|TypedArray|Object)} output array 44 * 45 * @example 46 * var pow = require( '@stdlib/math/base/special/pow' ); 47 * 48 * var out = normalize( [ 0.0, 0 ], 3.14e-319 ); 49 * // returns [ 1.4141234400356668e-303, -52 ] 50 * 51 * var y = out[ 0 ]; 52 * var exp = out[ 1 ]; 53 * 54 * var bool = ( y*pow(2.0,exp) === 3.14e-319 ); 55 * // returns true 56 * 57 * @example 58 * var out = normalize( [ 0.0, 0 ], 0.0 ); 59 * // returns [ 0.0, 0 ]; 60 * 61 * @example 62 * var out = normalize( [ 0.0, 0 ], Infinity ); 63 * // returns [ Infinity, 0 ] 64 * 65 * @example 66 * var out = normalize( [ 0.0, 0 ], -Infinity ); 67 * // returns [ -Infinity, 0 ] 68 * 69 * @example 70 * var out = normalize( [ 0.0, 0 ], NaN ); 71 * // returns [ NaN, 0 ] 72 */ 73 function normalize( out, x ) { 74 if ( isnan( x ) || isInfinite( x ) ) { 75 out[ 0 ] = x; 76 out[ 1 ] = 0; 77 return out; 78 } 79 if ( x !== 0.0 && abs( x ) < FLOAT64_SMALLEST_NORMAL ) { 80 out[ 0 ] = x * SCALAR; 81 out[ 1 ] = -52; 82 return out; 83 } 84 out[ 0 ] = x; 85 out[ 1 ] = 0; 86 return out; 87 } 88 89 90 // EXPORTS // 91 92 module.exports = normalize;