Rather than using a decimal step directly, it's much safer to express this in terms of how many points you want. Otherwise, floating-point rounding error is likely to give you a wrong result.
You can use the linspace function from the NumPy library (which isn't part of the standard library but is relatively easy to obtain). linspace
takes a number of points to return, and also lets you specify whether or not to include the right endpoint:
>>> np.linspace(0,1,11)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
>>> np.linspace(0,1,10,endpoint=False)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
If you really want to use a floating-point step value, you can, with numpy.arange
.
>>> import numpy as np
>>> np.arange(0.0, 1.0, 0.1)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
Floating-point rounding error will cause problems, though. Here's a simple case where rounding error causes arange
to produce a length-4 array when it should only produce 3 numbers:
>>> numpy.arange(1, 1.3, 0.1)
array([1. , 1.1, 1.2, 1.3])
Best Answer
Let's say you want to scale a range
[min,max]
to[a,b]
. You're looking for a (continuous) function that satisfiesIn your case,
a
would be 1 andb
would be 30, but let's start with something simpler and try to map[min,max]
into the range[0,1]
.Putting
min
into a function and getting out 0 could be accomplished withSo that's almost what we want. But putting in
max
would give usmax - min
when we actually want 1. So we'll have to scale it:which is what we want. So we need to do a translation and a scaling. Now if instead we want to get arbitrary values of
a
andb
, we need something a little more complicated:You can verify that putting in
min
forx
now givesa
, and putting inmax
givesb
.You might also notice that
(b-a)/(max-min)
is a scaling factor between the size of the new range and the size of the original range. So really we are first translatingx
by-min
, scaling it to the correct factor, and then translating it back up to the new minimum value ofa
.Hope this helps.