time-to-botec

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

mult2.js (1762B)


      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 // VARIABLES //
     22 
     23 var MAX_ITER = 149; // 127+22 (subnormals) => BIAS+NUM_SIGNFICAND_BITS-1
     24 var MAX_BITS = 24; // only 23 bits for fraction
     25 
     26 
     27 // MAIN //
     28 
     29 /**
     30 * Converts a fraction to a literal bit representation using the multiply-by-2 algorithm.
     31 *
     32 * @private
     33 * @param {number} x - number less than 1
     34 * @returns {BinaryString} bit representation
     35 *
     36 * @example
     37 * var v = mult2( 0.234375 );
     38 * // returns '001111'
     39 *
     40 * @example
     41 * var v = mult2( 0.0 );
     42 * // returns ''
     43 */
     44 function mult2( x ) {
     45 	var str;
     46 	var y;
     47 	var i;
     48 	var j;
     49 
     50 	str = '';
     51 	if ( x === 0.0 ) {
     52 		return str;
     53 	}
     54 	j = MAX_ITER;
     55 
     56 	// Each time we multiply by 2 and find a ones digit, add a '1'; otherwise, add a '0'..
     57 	for ( i = 0; i < MAX_ITER; i++ ) {
     58 		y = x * 2.0;
     59 		if ( y >= 1.0 ) {
     60 			x = y - 1.0;
     61 			str += '1';
     62 			if ( j === MAX_ITER ) {
     63 				j = i; // first '1'
     64 			}
     65 		} else {
     66 			x = y;
     67 			str += '0';
     68 		}
     69 		// Stop when we have no more decimals to process or in the event we found a fraction which cannot be represented in a finite number of bits...
     70 		if ( y === 1.0 || i-j > MAX_BITS ) {
     71 			break;
     72 		}
     73 	}
     74 
     75 	return str;
     76 }
     77 
     78 
     79 // EXPORTS //
     80 
     81 module.exports = mult2;