Created
February 24, 2024 17:01
-
-
Save linadk/9a6a8d4b661a1efc8ae798b432ee44d2 to your computer and use it in GitHub Desktop.
A Float64 linspace(...) function that can handle ascending/descending
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Generate a Float64 array of linearly spaced values. | |
* @param start Number representing the starting point of this linear space. | |
* @param stop Number Representing the endpoint of this linear space. | |
* @param step Step size through the linear space. Always positive, sign determined by range. | |
* @returns An array of evenly spaced elements specified by start,stop,step. | |
* @example | |
* ``` | |
* const s = linspace(0,1,0.1) | |
* > [0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1] | |
* ``` | |
* @remark Note that floating point values may not be exact. For comparisons it's recommended to | |
* reduce precision with toFixed(n) or use a tolerance. | |
*/ | |
export function linspace(start:number,stop:number,step:number):Float64Array{ | |
const D = Math.abs(stop-start) | |
step = Math.abs(step) | |
// Sanity checks | |
if(D === 0 || D < step || step === 0){ return new Float64Array(0) } | |
const L = Math.ceil(D/step)+1 // number of steps | |
let A = new Float64Array(L) | |
// If we are descending, negate step | |
if((stop-start)<0){ | |
step=-step | |
} | |
if(L===1){ | |
A[0]=start; return A; | |
} | |
if(L===2){ | |
A[0]=start; A[1]=stop; return A; | |
} | |
A[0] = start | |
A[L-1] = stop | |
for(let i=1; i<L-1; i++){ | |
A[i] = A[i-1]+step | |
} | |
return A | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment