>>> def drange(start, stop, step):... r = start... while r < stop:... yield r... r += step...>>> i0=drange(0.0, 1.0, 0.1)>>> ["%g" % x for x in i0]['0', '0.1', '0.2', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9', '1']>>>
def seq(start, stop, step=1):n = int(round((stop - start)/float(step)))if n > 1:return([start + step*i for i in range(n+1)])elif n == 1:return([start])else:return([])
## frange.pyfrom math import ceil# find best range function available to version (2.7.x / 3.x.x)try:_xrange = xrangeexcept NameError:_xrange = range
def frange(start, stop = None, step = 1):"""frange generates a set of floating point values over therange [start, stop) with step size step
frange([start,] stop [, step ])"""
if stop is None:for x in _xrange(int(ceil(start))):yield xelse:# create a generator expression for the index valuesindices = (i for i in _xrange(0, int((stop-start)/step)))# yield resultsfor i in indices:yield start + step*i
## drange.pyimport decimalfrom math import ceil# find best range function available to version (2.7.x / 3.x.x)try:_xrange = xrangeexcept NameError:_xrange = range
def drange(start, stop = None, step = 1, precision = None):"""drange generates a set of Decimal values over therange [start, stop) with step size step
drange([start,] stop, [step [,precision]])"""
if stop is None:for x in _xrange(int(ceil(start))):yield xelse:# find precisionif precision is not None:decimal.getcontext().prec = precision# convert values to decimalsstart = decimal.Decimal(start)stop = decimal.Decimal(stop)step = decimal.Decimal(step)# create a generator expression for the index valuesindices = (i for i in _xrange(0,((stop-start)/step).to_integral_value()))# yield resultsfor i in indices:yield float(start + step*i)
## testranges.pyimport frangeimport drangelist(frange.frange(0, 2, 0.5)) # [0.0, 0.5, 1.0, 1.5]list(drange.drange(0, 2, 0.5, precision = 6)) # [0.0, 0.5, 1.0, 1.5]list(frange.frange(3)) # [0, 1, 2]list(frange.frange(3.5)) # [0, 1, 2, 3]list(frange.frange(0,10, -1)) # []
>>> step = .1>>> N = 10 # number of data points>>> [ x / pow(step, -1) for x in range(0, N + 1) ]
[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
或者,对于设定范围而不是设定数据点(例如连续函数),请使用:
>>> step = .1>>> rnge = 1 # NOTE range = 1, i.e. span of data points>>> N = int(rnge / step>>> [ x / pow(step,-1) for x in range(0, N + 1) ]
[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
要实现一个函数:将x / pow(step, -1)替换为f( x / pow(step, -1) ),并定义f。 例如:
>>> import math>>> def f(x):return math.sin(x)
>>> step = .1>>> rnge = 1 # NOTE range = 1, i.e. span of data points>>> N = int(rnge / step)>>> [ f( x / pow(step,-1) ) for x in range(0, N + 1) ]
[0.0, 0.09983341664682815, 0.19866933079506122, 0.29552020666133955, 0.3894183423086505,0.479425538604203, 0.5646424733950354, 0.644217687237691, 0.7173560908995228,0.7833269096274834, 0.8414709848078965]
import collections.abcimport numbers
class linspace(collections.abc.Sequence):"""linspace(start, stop, num) -> linspace object
Return a virtual sequence of num numbers from start to stop (inclusive).
If you need a half-open range, use linspace(start, stop, num+1)[:-1]."""def __init__(self, start, stop, num):if not isinstance(num, numbers.Integral) or num <= 1:raise ValueError('num must be an integer > 1')self.start, self.stop, self.num = start, stop, numself.step = (stop-start)/(num-1)def __len__(self):return self.numdef __getitem__(self, i):if isinstance(i, slice):return [self[x] for x in range(*i.indices(len(self)))]if i < 0:i = self.num + iif i >= self.num:raise IndexError('linspace object index out of range')if i == self.num-1:return self.stopreturn self.start + i*self.stepdef __repr__(self):return '{}({}, {}, {})'.format(type(self).__name__,self.start, self.stop, self.num)def __eq__(self, other):if not isinstance(other, linspace):return Falsereturn ((self.start, self.stop, self.num) ==(other.start, other.stop, other.num))def __ne__(self, other):return not self==otherdef __hash__(self):return hash((type(self), self.start, self.stop, self.num))