Created
July 15, 2021 17:42
-
-
Save russellbits/672921fe0e23673fa791911f79fb2a21 to your computer and use it in GitHub Desktop.
Produces a linear set (array) of numbers that are evenly spaced along the number line.
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
/** | |
* Produces a sequence (array) of numbers that are evenly spaced along the number line. | |
* @param {Number} x1 The first number in the sequence | |
* @param {Number} x2 The last number | |
* @param {Number} n The number of numbers in the sequence | |
* @param {Number} d What decimal place to round each element of the sequence | |
* @return {Array} The linearly spaced sequence | |
*/ | |
const linspace = (x1, x2, n, d) => { | |
n = n || 100 | |
d = d || 2 | |
const gap = (x2-x1)/(n-1) | |
let set = [] | |
// Generate each member of the set. | |
for (var i = 0; i < n; i++) { | |
set[i] = (x1 + (i * gap)) | |
} | |
// Round each member of the set to the desired length | |
let roundedSet = set.map(n => (Math.round(n * Math.pow(10, d)) / Math.pow(10,d))) | |
return roundedSet | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment