lowest absolute value

I have 4 variables and need to get whichever has the lowest absolute value.
I tried


x = min(abs(a), abs(b), abs(c), abs(d))

the problem is this way I lose the pos/neg sign

So, I ended up doing this:

if abs(a) <= abs(b):
    x = a
    if abs(a) <= abs(c):
        x = a
        if abs(a) <= abs(d):
            x = a
        else:
            x = d
    else:
        x = c
else:
    x = b
    if abs(b) <= abs(c):
        x = b
        if abs(b) <= abs(d):
            x = b
        else:
            x = d
    else:
        x = c
        if abs(c) <= abs(d):
            x = c
        else:
            x = d

This works fine, but out of curiosity, how would I do it with a thousand variables?

You can try this, but it uses lists rather than individual variables. I’d assume if you had 1000 of them, you’d want them in a list.

import bpy, random

l=[]
for i in range(50): #this loop generates 50 fake values in the range of +25 to -25
    l.append(random.uniform(-25,25))




min = 25   # initialize the minimum to the highest possible value 


for j in l:
    ja = abs(j) #calculate abs
    if ja<min:  #compare abs to current min
        min = ja    #update min if current abs is lower than the current min




print('min: '+str(min)) #do whatever you want with your lowest absolute value

I run your script a hundred times and it always returned a positive value. The problem is that I need to know if the original value is positive or negative.

ah, right, I forgot about that part, I’ll update.

edit: here is the updated code:

import bpy, random

l=[]
for i in range(50): #this loop generates 50 fake values in the range of +25 to -25
    l.append(random.uniform(-25,25))




min = 25   # initialize the minimum to the highest possible value 
value = 0   #initialize output variable


for j in l:
    ja = abs(j) #calculate abs
    if ja<min:  #compare abs to current min
        min = ja    #update min if current abs is lower than the current min
        value = j




print('min: '+str(value)) #do whatever you want with your lowest absolute value

Thanks a lot.

Imo, best way for python is to use list.sort() or sorted() with a key.
In your case you need to use abs() method as a key.

Here an example from stackoverflow.

The example above returns a new list.
You can also sort in place within your list object.

In [1]: myList = [20, -5, 10, 3, 4, -7]
In [2]: myList.sort(key=abs)
In [3]: myList
Out[3]: [3, 4, -5, -7, 10, 20]

erdinc, thank you too