I need to operate with variables that can be either positive or negative values, in a way that a method should be able to add or substract its absolute value, but without changing its sign.
I have the following code to do something alike:
public static class FloatExtensions
{
public static float sumToItsAbsolute(this float currentValue, float summedValue)
{
float currentAbsoluteValue = Math.Abs(currentValue);
return (currentValue / currentAbsoluteValue) * (currentAbsoluteValue summedValue);
}
}
I can work with it, but I would like to know if there is a better approach.
EDIT: By "better", I mean more performant. And if there is no potential bugs I have not seen yet.
Thanks in advance.
CodePudding user response:
If you spend a little time looking around the documentation of the Math class (which you are already using, so it is known to you already), you will notice that it offers a many handy functions. Among them a function to get the sign of a value.
Thus, instead of doing v / Math.Abs(v)
to get the sign of v
as values -1 or 1 (functional and creative, but cumbersome, and perhaps even prone to precision errors IEEE floating point operations might suffer from), you could just do Math.Sign(v)
to get the sign.
With regards to bugs: I'd like to throw the ball back into your court and like to encourage you to think a little bit about the behavior of your code for yourself first. Note how your code is doing a division and a multiplication of a sum. Can you find values for currentValue where either the division or the multiplication might fail or yield the wrong result?
Performancewise, i really doubt this function is what would make your program slower than you desire. If your program is behaving slower than expected in some aspects, use a profiler to figure out the actual part(s) in your program that account for most of the performance costs instead of eyeballing and blind-guessing it.