linspace.js (2262B)
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 isNumber = require( '@stdlib/assert/is-number' ).isPrimitive; 24 var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; 25 var isnan = require( '@stdlib/math/base/assert/is-nan' ); 26 27 28 // MAIN // 29 30 /** 31 * Generates a linearly spaced numeric array. 32 * 33 * @param {number} x1 - first array value 34 * @param {number} x2 - last array value 35 * @param {NonNegativeInteger} [len=100] - length of output array 36 * @throws {TypeError} first argument must be numeric 37 * @throws {TypeError} second argument must be numeric 38 * @throws {TypeError} third argument must be a nonnegative integer 39 * @returns {Array} linearly spaced numeric array 40 * 41 * @example 42 * var arr = linspace( 0, 100, 6 ); 43 * // returns [ 0, 20, 40, 60, 80, 100 ] 44 */ 45 function linspace( x1, x2, len ) { 46 var arr; 47 var end; 48 var tmp; 49 var d; 50 var i; 51 if ( !isNumber( x1 ) || isnan( x1 ) ) { 52 throw new TypeError( 'invalid argument. Start must be numeric. Value: `' + x1 + '`.' ); 53 } 54 if ( !isNumber( x2 ) || isnan( x2 ) ) { 55 throw new TypeError( 'invalid argument. Stop must be numeric. Value: `' + x2 + '`.' ); 56 } 57 if ( arguments.length < 3 ) { 58 len = 100; 59 } else { 60 if ( !isNonNegativeInteger( len ) ) { 61 throw new TypeError( 'invalid argument. Length must be a nonnegative integer. Value: `' + len + '`.' ); 62 } 63 if ( len === 0 ) { 64 return []; 65 } 66 } 67 // Calculate the increment: 68 end = len - 1; 69 d = ( x2-x1 ) / end; 70 71 // Build the output array... 72 arr = []; 73 tmp = x1; 74 arr.push( tmp ); 75 for ( i = 1; i < end; i++ ) { 76 tmp += d; 77 arr.push( tmp ); 78 } 79 arr.push( x2 ); 80 return arr; 81 } 82 83 84 // EXPORTS // 85 86 module.exports = linspace;