time-to-botec

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

roundb.js (2113B)


      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 round = require( './../../../../base/special/round' );
     27 var roundn = require( './../../../../base/special/roundn' );
     28 
     29 
     30 // MAIN //
     31 
     32 /**
     33 * Rounds a numeric value to the nearest multiple of \\(b^n\\) on a linear scale.
     34 *
     35 * @param {number} x - input value
     36 * @param {integer} n - integer power
     37 * @param {PositiveInteger} b - base
     38 * @returns {number} rounded value
     39 *
     40 * @example
     41 * // Round a value to 2 decimal places:
     42 * var v = roundb( 3.141592653589793, -2, 10 );
     43 * // returns 3.14
     44 *
     45 * @example
     46 * // If n = 0 or b = 1, `roundb` behaves like `round`:
     47 * var v = roundb( 3.141592653589793, 0, 2 );
     48 * // returns 3.0
     49 *
     50 * @example
     51 * // Round a value to the nearest multiple of two:
     52 * var v = roundb( 5.0, 1, 2 );
     53 * // returns 6.0
     54 */
     55 function roundb( x, n, b ) {
     56 	var y;
     57 	var s;
     58 	if (
     59 		isnan( x ) ||
     60 		isnan( n ) ||
     61 		isnan( b ) ||
     62 		b <= 0 ||
     63 		isInfinite( n ) ||
     64 		isInfinite( b )
     65 	) {
     66 		return NaN;
     67 	}
     68 	if ( isInfinite( x ) || x === 0.0 ) {
     69 		return x;
     70 	}
     71 	if ( b === 10 ) {
     72 		return roundn( x, n );
     73 	}
     74 	if ( n === 0 || b === 1 ) {
     75 		return round( x );
     76 	}
     77 	s = pow( b, -n );
     78 
     79 	// Check for overflow:
     80 	if ( isInfinite( s ) ) {
     81 		return x;
     82 	}
     83 	y = round( x * s ) / s;
     84 
     85 	// Check for overflow:
     86 	if ( isInfinite( y ) ) {
     87 		return x;
     88 	}
     89 	return y;
     90 }
     91 
     92 
     93 // EXPORTS //
     94 
     95 module.exports = roundb;