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.
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