Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Absolute value in vb.net

How do you get the absolute value of a number in vb.net?

Is there a function built in? I know I can simply code a function myself, but I want to know if there is one already there first. It seems so simple, I could probably make it in three lines, so I would be surprised if there isnt one....

Thanks!

like image 608
Cyclone Avatar asked Sep 01 '09 23:09

Cyclone


1 Answers

At the risk of being down-voted, you may want to write your own absolute value method, depending on what you're using it for. The following code snippet (sorry it's in C#, but the same principle applies):

short i = -32768;
int iAbs = Math.Abs(i);

will happily compile, but when run, the second line will throw an OverflowException with the helpful message "Negating the minimum value of a twos complement number is invalid." In this case, because i is type short, the compiler chooses the overload of Math.Abs that accepts a short and returns a short, and +32768 is not a valid short, so the method throws the exception even if you thought you were anticipating this problem by making iAbs an int.

This snippet:

short i = -32768;
int iAbs = Math.Abs((int)i);

will compile and execute without an exception, but it's kind of clunky to code this way. In my opinion, this is a very sneaky error because it's so rarely encountered in the real world (since there's only one value for each type that will generate this exception). I, unfortunately, run into this error whenever I use Math.Abs for normalizing audio data (which is usually a short[] array), so I've gotten in the habit of writing my own wrapper around Math.Abs that handles all of this for me and just returns a double:

public double AbsThatDoesntSuck(short value)
{
    return Math.Abs((double)value);
}

with overloads for whatever other type I need to handle. I kind of understand why Math.Abs was written to behave this way, but it can definitely bite the behinds of the unaware.

like image 60
MusiGenesis Avatar answered Sep 19 '22 02:09

MusiGenesis