Create list of numbers mirrored around zero (python) -


i think should simple question... it's been holding me time :(

i wish create list of numbers, centred (as were) on zero, input specifies maximum , increment. so,

max = 100 increment = 1  

would return

[-100,-99,-98,...,-1,0,1,...,99,100] 

and

max = 35 increment = 0.2 

would return

[-35.0,-34.8,...,-0.2,0,0.2,...34.8,35.0] 

if increment doesn't divide neatly maximum, needs make short last step (e.g. if counting 1 in 0.3 increments, run [-1.0,-0.6,-0.3,0.0,0.3,0.6,0.9,1.0]

list(numpy.linspace()) seems way go seem having complete mental block on how make work in way described simplest cases.

suggestions appreciated!

edit: own solution was

def mylist(stop,step):     = list(np.arange(0,-stop,-step))+[-stop]     a.reverse()     b = list(a)     c = list(np.arange(0,stop,step))+[stop]     d = b+c     d.remove(0)     e = list(d)     return e 

which horribly clunky, can see.

the best answer was:

def mirrored(maxval, inc):     x = np.arange(inc, maxval, inc)     if x[-1] != maxval:         x = np.r_[x, maxval]     return np.r_[-x[::-1], 0, x] 

but going have google little more understand why works (also not sure if want round... input increment might legitimately specified more 1 decimal place)

if want strictly mirrored around 0, (i.e. include 0 , endpoints, , symmetric 0) you'll need couple of steps.

first off, aware of @npe's comment above. floating point math not same decimal math!! may seem beside point, will bite in circumstances.

there's more 1 way this. want have of numbers evenly spaced, or stick increment , violate @ endpoints?. approach takes latter of two.

import numpy np  def mirrored(maxval, inc=1):     x = np.arange(inc, maxval, inc)     if x[-1] != maxval:         x = np.r_[x, maxval]     return np.r_[-x[::-1], 0, x]  print mirrored(1, 0.3) 

this yields:

[-1.  -0.9 -0.6 -0.3  0.   0.3  0.6  0.9  1. ] 

if want of numbers evenly spaced (but not exact increment specify), use linspace:

import numpy np  def mirrored2(maxval, inc=1):     return np.linspace(-maxval, maxval, 2*maxval // inc)  print mirrored2(1, 0.3) 

this yields:

[-1.  -0.6 -0.2  0.2  0.6  1. ] 

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -