[PYTHON] double precision range

This return a double precision interator like the built-in range function.

class drange :
    """
    return double precision range.
    """
    def __init__(self,nx,sx,ex) :
        # check type
        if   type(nx) is not type(1)  : raise TypeError
        elif type(sx) is not type(1.) : raise TypeError
        elif type(ex) is not type(1.) : raise TypeError
        # initialize
        self.nx, self.sx, self.ex = nx, sx, ex
        self.dx, self.i = ( ex - sx ) / float(nx), -1

    def __iter__(self) : return self

    def next(self) :
        self.i += 1
        if self.i > self.nx-1 :
            self.i = -1
            raise StopIteration
        else :
            return self.sx + self.dx * float(self.i)

if __name__ == "__main__" :
    print [ x for x in drange(2**3,1.,2.) ]
    dx = drange(3,1.,2.)
    for x  in dx :
        print dx.i, x

results

[1.0, 1.125, 1.25, 1.375, 1.5, 1.625, 1.75, 1.875]
0 1.0
1 1.33333333333
2 1.66666666667

Recommended Posts

double precision range
range