I'm looking for something similar to numpy.linspace to generate an array of numbers based on a starting value, an ending value and the desired number of values in the array.
Example:
start=2.0, end=3.0, num=5
result = [2.0, 2.25, 2.5 , 2.75, 3.0]
I've come across this, but it separates the range based on the steps between.
Does JavaScript have a built-in method to accomplish this?
As others mentioned, there isn’t any built-in function in JavaScript, but here's one way you can implement it yourself. This specific example is a bit verbose so you can see exactly what's going on.
function makeArr(startValue, stopValue, cardinality) {
var arr = [];
var step = (stopValue - startValue) / (cardinality - 1);
for (var i = 0; i < cardinality; i++) {
arr.push(startValue + (step * i));
}
return arr;
}
console.log(makeArr(2, 3, 5));
console.log(makeArr(5, 10, 5));
console.log(makeArr(5, 10, 6));
console.log(makeArr(5, 31, 4));
If you want the numbers to be rounded to two decimal places, you can change the arr.push(...)
line to the following:
arr.push(parseFloat((currValue + (step * i)).toFixed(2)));
Or
arr.push(Math.round((currValue + (step * i)) * 100) / 100);
You can make use of Array.from
instead of manually pushing to the array:
function linspace(start, stop, num, endpoint = true) {
const div = endpoint ? (num - 1) : num;
const step = (stop - start) / div;
return Array.from({length: num}, (_, i) => start + step * i);
}
Note that this won't work for num=1 and endpoint=true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With