normalize.js (2318B)
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 FLOAT32_SMALLEST_NORMAL = require( '@stdlib/constants/float32/smallest-normal' ); 24 var PINF = require( '@stdlib/constants/float32/pinf' ); 25 var NINF = require( '@stdlib/constants/float32/ninf' ); 26 var abs = require( '@stdlib/math/base/special/abs' ); 27 var toFloat32 = require( './../../../../float64/base/to-float32' ); 28 29 30 // VARIABLES // 31 32 // (1<<32) 33 var SCALAR = 8388608; 34 35 36 // MAIN // 37 38 /** 39 * Returns a normal number `y` and exponent `exp` satisfying \\(x = y \cdot 2^\mathrm{exp}\\). 40 * 41 * @private 42 * @param {(Array|TypedArray|Object)} out - output array 43 * @param {number} x - single-precision floating-point number 44 * @returns {(Array|TypedArray|Object)} output array 45 * 46 * @example 47 * var toFloat32 = require( '@stdlib/number/float64/base/to-float32' ); 48 * 49 * var v = normalizef( [ 0.0, 0 ], toFloat32( 1.401e-45 ) ); 50 * // returns [ 1.1754943508222875e-38, -23 ] 51 * 52 * @example 53 * var v = normalizef( [ 0.0, 0 ], 0.0 ); 54 * // returns [ 0.0, 0 ]; 55 * 56 * @example 57 * var PINF = require( '@stdlib/constants/float32/pinf' ); 58 * 59 * var v = normalizef( [ 0.0, 0 ], PINF ); 60 * // returns [ +Infinity, 0 ] 61 * 62 * @example 63 * var NINF = require( '@stdlib/constants/float32/ninf' ); 64 * 65 * var v = normalizef( [ 0.0, 0 ], NINF ); 66 * // returns [ -Infinity, 0 ] 67 * 68 * @example 69 * var v = normalizef( [ 0.0, 0 ], NaN ); 70 * // returns [ NaN, 0 ] 71 */ 72 function normalizef( out, x ) { 73 if ( 74 x !== x || 75 x === PINF || 76 x === NINF 77 ) { 78 out[ 0 ] = x; 79 out[ 1 ] = 0; 80 return out; 81 } 82 if ( x !== 0.0 && abs( x ) < FLOAT32_SMALLEST_NORMAL ) { 83 x = toFloat32( x*SCALAR ); 84 out[ 0 ] = x; 85 out[ 1 ] = -23; 86 return out; 87 } 88 out[ 0 ] = x; 89 out[ 1 ] = 0; 90 return out; 91 } 92 93 94 // EXPORTS // 95 96 module.exports = normalizef;