floor2.js (2225B)
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 isnan = require( './../../../../base/assert/is-nan' ); 24 var isInfinite = require( './../../../../base/assert/is-infinite' ); 25 var pow = require( './../../../../base/special/pow' ); 26 var floor = require( './../../../../base/special/floor' ); 27 var ceil = require( './../../../../base/special/ceil' ); 28 var log2 = require( './../../../../base/special/log2' ); 29 var MAX_EXP = require( '@stdlib/constants/float64/max-base2-exponent' ); 30 var MIN_EXP_SUBNORMAL = require( '@stdlib/constants/float64/min-base2-exponent-subnormal' ); 31 var NINF = require( '@stdlib/constants/float64/ninf' ); 32 33 34 // MAIN // 35 36 /** 37 * Rounds a numeric value to the nearest power of two toward negative infinity. 38 * 39 * @param {number} x - input value 40 * @returns {number} rounded value 41 * 42 * @example 43 * var v = floor2( 3.141592653589793 ); 44 * // returns 2.0 45 * 46 * @example 47 * var v = floor2( 13.0 ); 48 * // returns 8.0 49 * 50 * @example 51 * var v = floor2( -0.314 ); 52 * // returns -0.5 53 */ 54 function floor2( x ) { 55 var sign; 56 var p; 57 if ( 58 isnan( x ) || 59 isInfinite( x ) || 60 x === 0.0 61 ) { 62 return x; 63 } 64 if ( x < 0 ) { 65 x = -x; 66 sign = -1.0; 67 } else { 68 sign = 1.0; 69 } 70 // Solve the equation `2^p = x` for `p`: 71 p = log2( x ); 72 73 // If provided the smallest subnormal, no rounding possible: 74 if ( p === MIN_EXP_SUBNORMAL ) { 75 return x; 76 } 77 // Determine a power of two which rounds the input value toward negative infinity: 78 if ( sign === 1.0 ) { 79 p = floor( p ); 80 } else { 81 p = ceil( p ); 82 } 83 // Handle overflow: 84 if ( p > MAX_EXP ) { 85 return NINF; 86 } 87 return sign * pow( 2.0, p ); 88 } 89 90 91 // EXPORTS // 92 93 module.exports = floor2;