time-to-botec

Benchmark sampling in different programming languages
Log | Files | Refs | README

trunc2.js (1557B)


      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 log2 = require( './../../../../base/special/log2' );
     28 
     29 
     30 // MAIN //
     31 
     32 /**
     33 * Rounds a numeric value to the nearest power of two toward zero.
     34 *
     35 * @param {number} x - input value
     36 * @returns {number} rounded value
     37 *
     38 * @example
     39 * var v = trunc2( 3.141592653589793 );
     40 * // returns 2.0
     41 *
     42 * @example
     43 * var v = trunc2( 13.0 );
     44 * // returns 8.0
     45 *
     46 * @example
     47 * var v = trunc2( -0.314 );
     48 * // returns -0.25
     49 */
     50 function trunc2( x ) {
     51 	var sign;
     52 	if (
     53 		isnan( x ) ||
     54 		isInfinite( x ) ||
     55 		x === 0.0
     56 	) {
     57 		return x;
     58 	}
     59 	if ( x < 0 ) {
     60 		x = -x;
     61 		sign = -1.0;
     62 	} else {
     63 		sign = 1.0;
     64 	}
     65 	return sign * pow( 2.0, floor( log2( x ) ) );
     66 }
     67 
     68 
     69 // EXPORTS //
     70 
     71 module.exports = trunc2;