Formula for rate that changes when negative

17 Views Asked by At

Is it possible to reduce this code to a single formula, rather than check if x is negative?

if (x < 0) value = (x   + length) * .5;
else       value = x   + (length * .5);

essentially, it's the same formula, but obvious the parenthesis change things.

The context is that I have an array of "enemy" objects in my program. I want to calculate how many turns it takes for them to finish the path. Each enemy has a "line position", which indicates at which turn they will spawn. Enemies with negative line position are placed that many tiles ahead on the board. The issue is that some enemies move 2 tiles at once when they are on the board, but each enemy only advances 1 place in line while waiting to be spawned. So, the number of turns it takes for each enemy to finish the path is different depending on their starting position. If they start negative, I simply calculate the length of the board, plus their position (minus, rather) and multiply it by their speed (in this case, .5). But, if they are waiting to spawn, it will take the length of the board times their speed PLUS their position, because their position is how many turns it takes to spawn.

Essentially, I'm working with a rate that changes when negative. Thinking as a linear graph, there is a large crease in the graph line at 0,0, because the rate changes.

Is there a way to simplify the formula, or are the if else statements necessary?

1

There are 1 best solutions below

2
On BEST ANSWER

Your function is equivalent to $$ \frac{3}{4} x + \frac{1}{4} |x| + \frac{L}{2} $$

If your program does everything else the same for $x$ on both sides of zero, this may be a worthwhile change.