ddot.js (2239B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2019 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 M = 5; 24 25 26 // MAIN // 27 28 /** 29 * Computes the dot product of `x` and `y`. 30 * 31 * @param {PositiveInteger} N - number of values over which to compute the dot product 32 * @param {Float64Array} x - first input array 33 * @param {integer} strideX - `x` stride length 34 * @param {Float64Array} y - second input array 35 * @param {integer} strideY - `y` stride length 36 * @returns {number} dot product of `x` and `y` 37 * 38 * @example 39 * var Float64Array = require( '@stdlib/array/float64' ); 40 * 41 * var x = new Float64Array( [ 4.0, 2.0, -3.0, 5.0, -1.0 ] ); 42 * var y = new Float64Array( [ 2.0, 6.0, -1.0, -4.0, 8.0 ] ); 43 * 44 * var z = ddot( x.length, x, 1, y, 1 ); 45 * // returns -5.0 46 */ 47 function ddot( N, x, strideX, y, strideY ) { 48 var dot; 49 var ix; 50 var iy; 51 var m; 52 var i; 53 54 dot = 0.0; 55 if ( N <= 0 ) { 56 return dot; 57 } 58 // Use unrolled loops if both strides are equal to `1`... 59 if ( strideX === 1 && strideY === 1 ) { 60 m = N % M; 61 62 // If we have a remainder, run a clean-up loop... 63 if ( m > 0 ) { 64 for ( i = 0; i < m; i++ ) { 65 dot += x[ i ] * y[ i ]; 66 } 67 } 68 if ( N < M ) { 69 return dot; 70 } 71 for ( i = m; i < N; i += M ) { 72 dot += ( x[ i ] * y[ i ] ) + ( x[ i+1 ] * y[ i+1 ] ) + ( x[ i+2 ] * y[ i+2 ] ) + ( x[ i+3 ] * y[ i+3 ] ) + ( x[ i+4 ] * y[ i+4 ] ); // eslint-disable-line max-len 73 } 74 return dot; 75 } 76 if ( strideX < 0 ) { 77 ix = ( 1-N ) * strideX; 78 } else { 79 ix = 0; 80 } 81 if ( strideY < 0 ) { 82 iy = ( 1-N ) * strideY; 83 } else { 84 iy = 0; 85 } 86 for ( i = 0; i < N; i++ ) { 87 dot += ( x[ ix ] * y[ iy ] ); 88 ix += strideX; 89 iy += strideY; 90 } 91 return dot; 92 } 93 94 95 // EXPORTS // 96 97 module.exports = ddot;