round2.js (2560B)
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 PINF = require( '@stdlib/constants/float64/pinf' ); 32 33 34 // VARIABLES // 35 36 // 2^1023: 37 var HUGE = pow( 2.0, MAX_EXP ); 38 var HALF_HUGE = HUGE / 2.0; 39 40 41 // MAIN // 42 43 /** 44 * Rounds a numeric value to the nearest power of two on a linear scale. 45 * 46 * @param {number} x - input value 47 * @returns {number} rounded value 48 * 49 * @example 50 * var v = round2( 3.141592653589793 ); 51 * // returns 4.0 52 * 53 * @example 54 * var v = round2( 13.0 ); 55 * // returns 16.0 56 * 57 * @example 58 * var v = round2( -0.314 ); 59 * // returns -0.25 60 */ 61 function round2( x ) { 62 var sign; 63 var half; 64 var p1; 65 var p2; 66 var y1; 67 var y2; 68 var p; 69 if ( 70 isnan( x ) || 71 isInfinite( x ) || 72 x === 0.0 73 ) { 74 return x; 75 } 76 if ( x < 0 ) { 77 x = -x; 78 sign = -1.0; 79 } else { 80 sign = 1.0; 81 } 82 // Solve the equation `2^p = x` for `p`: 83 p = log2( x ); 84 85 // If provided the smallest subnormal, no rounding possible: 86 if ( p === MIN_EXP_SUBNORMAL ) { 87 return x; 88 } 89 // Find the previous and next integer powers: 90 p1 = floor( p ); 91 p2 = ceil( p ); 92 93 // Handle overflow: 94 if ( p1 === MAX_EXP ) { 95 if ( x - HUGE >= HALF_HUGE ) { 96 return sign * PINF; // sign-preserving 97 } 98 return sign * HUGE; 99 } 100 // Compute previous and next powers of two: 101 y1 = pow( 2.0, p1 ); 102 y2 = pow( 2.0, p2 ); 103 104 // Find the closest power of two: 105 half = ( y2 - y1 ) / 2.0; 106 if ( y1+half > x ) { 107 return sign * y1; 108 } 109 return sign * y2; 110 } 111 112 113 // EXPORTS // 114 115 module.exports = round2;