time-to-botec

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

dnrm2.js (1797B)


      1 /**
      2 * @license Apache-2.0
      3 *
      4 * Copyright (c) 2020 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 sqrt = require( '@stdlib/math/base/special/sqrt' );
     24 var abs = require( '@stdlib/math/base/special/abs' );
     25 var pow = require( '@stdlib/math/base/special/pow' );
     26 
     27 
     28 // MAIN //
     29 
     30 /**
     31 * Computes the L2-norm of a double-precision floating-point vector.
     32 *
     33 * @param {PositiveInteger} N - number of values over which to compute the L2-norm
     34 * @param {Float64Array} x - input array
     35 * @param {PositiveInteger} stride - stride length
     36 * @returns {number} L2-norm of `x`
     37 *
     38 * @example
     39 * var Float64Array = require( '@stdlib/array/float64' );
     40 *
     41 * var x = new Float64Array( [ 1.0, -2.0, 2.0 ] );
     42 * var N = 3;
     43 *
     44 * var z = dnrm2( N, x, 1 );
     45 * // returns 3.0
     46 */
     47 function dnrm2( N, x, stride ) {
     48 	var scale;
     49 	var ssq;
     50 	var ax;
     51 	var i;
     52 
     53 	if ( N <= 0 || stride <= 0 ) {
     54 		return 0.0;
     55 	}
     56 	if ( N === 1 ) {
     57 		return abs( x[ 0 ] );
     58 	}
     59 	scale = 0.0;
     60 	ssq = 1.0;
     61 	N *= stride;
     62 	for ( i = 0; i < N; i += stride ) {
     63 		if ( x[ i ] !== 0.0 ) {
     64 			ax = abs( x[ i ] );
     65 			if ( scale < ax ) {
     66 				ssq = 1.0 + ( ssq * pow( scale/ax, 2 ) );
     67 				scale = ax;
     68 			} else {
     69 				ssq += pow( ax/scale, 2 );
     70 			}
     71 		}
     72 	}
     73 	return scale * sqrt( ssq );
     74 }
     75 
     76 
     77 // EXPORTS //
     78 
     79 module.exports = dnrm2;