python 3a np arange decimal places

Solutions on MaxInterview for python 3a np arange decimal places by the best coders in the world

showing results for - "python 3a np arange decimal places"
Sabrina
27 Jul 2017
1# It's embarrassing that python's range accumulate rounding errors
2# when using decimal step.
3# It's easy to implement a generator that does this even without accumulating
4# rounding errors.
5#
6# Lot of suggestions were made at  https://stackoverflow.com/questions/477486/how-to-use-a-decimal-range-step-value
7# Going through the forum, a general solution is presented below.
8# The seq function use generates ranges with decimal step without rounding error
9
10
11def seq(start, stop, step=1):
12    n = int(round((stop - start)/float(step)))
13    const = pow(step,-1)
14    if n > 1:
15        return([start + (i/const) for i in range(n+1)])
16    elif n == 1:
17        return([start])
18    else:
19        return([])
20      
21      
22
23# The seq function above works fine though may have performance issue 
24# because of the use of power and division. Its therefore advice to
25# use it only when rounding error is of atmost concern.