memyself
memyself

Reputation: 12628

generic algorithm to force range to go through zero

I'm looking for a generic algorithm which, given the range values start and end will generate a list of numbers, but the numbers must go through zero.. Here's my current code:

end = 78
start = -1 * end
step_size = 16
numbers = range(start, end+step_size, step_size)

$ numbers
Out[90]: [-78, -62, -46, -30, -14, 2, 18, 34, 50, 66, 82]

so in this particular case, I would subtract 2 from each number, so that the numbers have one zero value. But how could I do this more generally? I'm doing this to calculate the y-tic locations of a graph, and therefore I want them to go through zero once.

Upvotes: 0

Views: 103

Answers (2)

Andrew Clark
Andrew Clark

Reputation: 208555

start % step_size should be the required offset:

>>> end = 78
>>> start = -1 * end
>>> step_size = 16
>>> range(start-(start%step_size), end+step_size, step_size)
[-80, -64, -48, -32, -16, 0, 16, 32, 48, 64, 80]

Examples:

def get_range(end, step_size):
    start = -1 * end
    return range(start-(start%step_size), end+step_size, step_size)

>>> get_range(23, 4)
[-24, -20, -16, -12, -8, -4, 0, 4, 8, 12, 16, 20, 24]
>>> get_range(19, 11)
[-22, -11, 0, 11, 22]
>>> get_range(103, 32)
[-128, -96, -64, -32, 0, 32, 64, 96, 128]

Upvotes: 4

Dhara
Dhara

Reputation: 6767

Find the minimum of the absolute value of the list, subtract it from each element of the list. This isn't the most optimal solution, but it's quick and dirty and it works:

(I used numpy because it's more efficient than lists, and if you're using matplotlib, you probably have numpy)

>>> from numpy import *
>>> a = arange(-10, 20, 3)
>>> b = argmin([abs(_) for _ in a])
>>> a-=a[b]
>>> a
array([-9, -6, -3,  0,  3,  6,  9, 12, 15, 18])

Upvotes: 0

Related Questions