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