time-to-botec

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

ndarray.js (1853B)


      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 {integer} stride - stride length
     36 * @param {NonNegativeInteger} offset - starting index
     37 * @returns {number} L2-norm
     38 *
     39 * @example
     40 * var floor = require( '@stdlib/math/base/special/floor' );
     41 *
     42 * var x = [ 2.0, 1.0, 2.0, -2.0, -2.0, 2.0, 3.0, 4.0 ];
     43 * var N = floor( x.length / 2 );
     44 *
     45 * var z = gnrm2( N, x, 2, 1 );
     46 * // returns 5.0
     47 */
     48 function gnrm2( N, x, stride, offset ) {
     49 	var scale;
     50 	var ssq;
     51 	var ax;
     52 	var ix;
     53 	var i;
     54 
     55 	if ( N <= 0 ) {
     56 		return 0.0;
     57 	}
     58 	if ( N === 1 ) {
     59 		return abs( x[ offset ] );
     60 	}
     61 	ix = offset;
     62 	scale = 0.0;
     63 	ssq = 1.0;
     64 	for ( i = 0; i < N; i++ ) {
     65 		if ( x[ ix ] !== 0.0 ) {
     66 			ax = abs( x[ ix ] );
     67 			if ( scale < ax ) {
     68 				ssq = 1.0 + ( ssq * pow( scale/ax, 2 ) );
     69 				scale = ax;
     70 			} else {
     71 				ssq += pow( ax/scale, 2 );
     72 			}
     73 		}
     74 		ix += stride;
     75 	}
     76 	return scale * sqrt( ssq );
     77 }
     78 
     79 
     80 // EXPORTS //
     81 
     82 module.exports = gnrm2;