What is an easy way to generate an array that has values with a fixed distance between them?
For example:
1, 4, 7, 10,... etc
I need to be able to set start, end, and step distance.
Creating Sequential Arrays: arange and linspace The linspace function allows you to generate evenly-spaced points within a user-specified interval ( and are included in the interval).
The most straightforward option that Python offers is the built-in range() . The function call range(10) returns an object that produces the sequence from 0 to 9 , which is an evenly spaced range of numbers.
arange() NumPy arange() is one of the array creation routines based on numerical ranges. It creates an instance of ndarray with evenly spaced values and returns the reference to it.
linspace) is a tool in Python for creating numeric sequences. It's somewhat similar to the NumPy arange function, in that it creates sequences of evenly spaced numbers structured as a NumPy array.
Try using Range.step
:
> (1..19).step(3).to_a
=> [1, 4, 7, 10, 13, 16, 19]
In Ruby 1.9:
1.step(12).to_a #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
1.step(12,3).to_a #=> [1, 4, 7, 10]
Or you can splat instead of to_a
:
a = *1.step(12,3) #=> [1, 4, 7, 10]
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