Search code examples
gdscript

How to "absolute-ly" take from a number? (How to offset a number?)


Essentially what I need to do is a - b, but I don't know what either will be and if a is positive then how can I take b from a in a "absolute" way?

What I mean is for example A = 10 and B = 5. Answer is obviously 5. If A was now -10, the answer is now -5. The answer leans towards 0 no matter what the numbers are. I heavily want to avoid using an if statement if I can.

My original idea was a - (b * (b / abs(b))). But b can be 0, and then div by 0 error occurs.

EDIT: A better way of saying it is I want to offset the result by an amount instead of math.


Solution

  • So do I understand correctly that whatever the value of A, you want it to bias towards zero (based on the initial value of A) by the value of B?

    So given: A=10 and B=5, the result will be 5. A=-10 and B=5, the result will be -5. A=-5 and B=-10, the result will be 5 (because it is offset by 10, towards zero from a starting point of -5).

    Effectively the sign of B is immaterial because it specifies an offset towards zero in all cases.

    What of the case where A=0 and B is non-zero? Is the result supposed to be undefined (because the appropriate direction of offset cannot be inferred), or is it supposed to be zero?

    The formula for the latter case would be (ABS(A) - ABS(B)) * SIGN(A)) (assuming that the sign function returns 0 when A is zero).