Friday, July 8, 2011

python sequence float vs int

Python has a nifty little way to generate a sequence of numbers:

sequence = range(0, 10, 1)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

However, this doesn't work when the step value is float. For that purpose, use numpy's arange function:

import numpy as np
sequence = np.arange(0,1,0.1)

array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9])

For more interesting ways, including using generators, check: http://stackoverflow.com/questions/477486/python-decimal-range-step-value

No comments:

Post a Comment