ndarray.js (2563B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 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 float64ToFloat32 = require( '@stdlib/number/float64/base/to-float32' ); 24 25 26 // VARIABLES // 27 28 var M = 4; 29 30 31 // MAIN // 32 33 /** 34 * Multiplies a vector `x` by a constant and adds the result to `y`. 35 * 36 * @param {PositiveInteger} N - number of elements 37 * @param {number} alpha - scalar 38 * @param {Float32Array} x - input array 39 * @param {integer} strideX - `x` stride length 40 * @param {NonNegativeInteger} offsetX - starting `x` index 41 * @param {Float32Array} y - destination array 42 * @param {integer} strideY - `y` stride length 43 * @param {NonNegativeInteger} offsetY - starting `y` index 44 * @returns {Float32Array} `y` 45 * 46 * @example 47 * var Float32Array = require( '@stdlib/array/float32' ); 48 * 49 * var x = new Float32Array( [ 1.0, 2.0, 3.0, 4.0, 5.0 ] ); 50 * var y = new Float32Array( [ 1.0, 1.0, 1.0, 1.0, 1.0 ] ); 51 * var alpha = 5.0; 52 * 53 * saxpy( x.length, alpha, x, 1, 0, y, 1, 0 ); 54 * // y => <Float32Array>[ 6.0, 11.0, 16.0, 21.0, 26.0 ] 55 */ 56 function saxpy( N, alpha, x, strideX, offsetX, y, strideY, offsetY ) { 57 var ix; 58 var iy; 59 var m; 60 var i; 61 if ( N <= 0 || alpha === 0.0 ) { 62 return y; 63 } 64 ix = offsetX; 65 iy = offsetY; 66 67 // Use unrolled loops if both strides are equal to `1`... 68 if ( strideX === 1 && strideY === 1 ) { 69 m = N % M; 70 71 // If we have a remainder, run a clean-up loop... 72 if ( m > 0 ) { 73 for ( i = 0; i < m; i++ ) { 74 y[ iy ] += float64ToFloat32( alpha * x[ ix ] ); 75 ix += strideX; 76 iy += strideY; 77 } 78 } 79 if ( N < M ) { 80 return y; 81 } 82 for ( i = m; i < N; i += M ) { 83 y[ iy ] += float64ToFloat32( alpha * x[ ix ] ); 84 y[ iy+1 ] += float64ToFloat32( alpha * x[ ix+1 ] ); 85 y[ iy+2 ] += float64ToFloat32( alpha * x[ ix+2 ] ); 86 y[ iy+3 ] += float64ToFloat32( alpha * x[ ix+3 ] ); 87 ix += M; 88 iy += M; 89 } 90 return y; 91 } 92 for ( i = 0; i < N; i++ ) { 93 y[ iy ] += float64ToFloat32( alpha * x[ ix ] ); 94 ix += strideX; 95 iy += strideY; 96 } 97 return y; 98 } 99 100 101 // EXPORTS // 102 103 module.exports = saxpy;