time-to-botec

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

gnrm2.js (1673B)


      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 vector.
     32 *
     33 * @param {PositiveInteger} N - number of values over which to compute the L2-norm
     34 * @param {NumericArray} x - input array
     35 * @param {PositiveInteger} stride - stride length
     36 * @returns {number} L2-norm
     37 *
     38 * @example
     39 * var x = [ 1.0, -2.0, 2.0 ];
     40 *
     41 * var z = gnrm2( x.length, x, 1 );
     42 * // returns 3.0
     43 */
     44 function gnrm2( N, x, stride ) {
     45 	var scale;
     46 	var ssq;
     47 	var ax;
     48 	var i;
     49 
     50 	if ( N <= 0 || stride <= 0 ) {
     51 		return 0.0;
     52 	}
     53 	if ( N === 1 ) {
     54 		return abs( x[ 0 ] );
     55 	}
     56 	scale = 0.0;
     57 	ssq = 1.0;
     58 	N *= stride;
     59 	for ( i = 0; i < N; i += stride ) {
     60 		if ( x[ i ] !== 0.0 ) {
     61 			ax = abs( x[ i ] );
     62 			if ( scale < ax ) {
     63 				ssq = 1.0 + ( ssq * pow( scale/ax, 2 ) );
     64 				scale = ax;
     65 			} else {
     66 				ssq += pow( ax/scale, 2 );
     67 			}
     68 		}
     69 	}
     70 	return scale * sqrt( ssq );
     71 }
     72 
     73 
     74 // EXPORTS //
     75 
     76 module.exports = gnrm2;