unitspace

Generate a linearly spaced numeric array whose elements increment by 1.

Usage

var unitspace = require( '@stdlib/array/base/unitspace' );

unitspace( start, stop, increment )

Generates a linearly spaced numeric array whose elements increment by 1.

var arr = unitspace( 0, 6 );
// returns [ 0, 1, 2, 3, 4, 5 ]

Notes

  • The output array is guaranteed to include the start value but does not include the stop value. Beware that values subsequent to the start value are subject to floating-point errors. Hence,

    var arr = unitspace( -0.7, 1 );
    // returns [ -0.7, ~0.3 ]
    

    where arr[1] is only guaranteed to be approximately equal to 0.3.

    If you desire more control over element precision, consider using roundn:

    var roundn = require( '@stdlib/math/base/special/roundn' );
    
    // Create an array subject to floating-point errors:
    var arr = unitspace( -10.7, 11.7 );
    
    // Round each value to the nearest hundredth:
    var i;
    for ( i = 0; i < arr.length; i++ ) {
        arr[ i ] = roundn( arr[ i ], -2 );
    }
    
    console.log( arr.join( '\n' ) );
    

Examples

var sort2hp = require( '@stdlib/blas/ext/base/gsort2hp' );
var filledBy = require( '@stdlib/array/base/filled-by' );
var randu = require( '@stdlib/random/base/randu' );
var unitspace = require( '@stdlib/array/base/unitspace' );

// Generate an array of random numbers:
var x = filledBy( 10, randu );

// Generate an array of indices:
var idx = unitspace( 0, x.length );

// Create a temporary array to avoid mutation:
var tmp = x.slice();

// Sort the index array according to the sort order of `x`:
sort2hp( x.length, 1, tmp, 1, idx, 1 );

console.log( x );
console.log( idx );
Did you find this page helpful?