Question

I am trying to convert the value 0 to 1 and 1 to -1, but without using if statements. I tried to do some math to map it to a new range but I am not able to do it for both parameters.

Is this doable?

It has to do this without hardcoded values in a collection though, so for example:

initial = 0 or 1;
final_value = (initial + 1) * -1;

So final value will be mapped to 1 or -1 depending on the initial value, using the same equation.

EDIT: I am basically trying to get rid of the if statement because this is shader code and my friend at work (shader programmer) said if statements slow down the execution so it's better to do things uniformly. Not sure if it makes sense.

Was it helpful?

Solution 2

1-(2*variable_value)

would give you those values ... but there is a strong chance this is not what you want ... because its really hard to tell what you want

since you have clarified that you want speed for shaders I figured I would add this info

In [3]: %timeit x= 1 if not random.randint(0,1) else -1 #if statement
1000000 loops, best of 3: 1.31 us per loop

In [4]: %timeit x= 1-(2*random.randint(0,1)) #simple math
1000000 loops, best of 3: 1.32 us per loop

In [5]: %timeit x= [1,-1][random.randint(0,1)] #array lookup
1000000 loops, best of 3: 1.41 us per loop

In [7]: %timeit x= arr[random.randint(0,1)]
1000000 loops, best of 3: 1.31 us per loop

I actually was a little surprised that the array lookup was slower (Actually only if you dont already have the array constructed)

OTHER TIPS

In Python:

arr = [1, -1]
mapped = arr[n]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top