Abs( )

Abs in Game Programming

Abs is a math function present in most BASIC dialects and in most game programming languages.

In mathematical terms, Abs() returns the absolute value of a number. In practical terms Abs() simply converts a negative number to a positive number. If the number is already positive, it simply returns the number. It will not turn a positive number to a negative number.

Abs() can be used to check the absolute distance between two points along a horizontal or vertical line and check if a number is positive or negative if no other function to do this available.

History

Abs() was a part of the original Dartmouth BASIC specification. Therefore it has been around as long as BASIC has.

Syntax

rnum = ABS ( num )

  • rnum - returned absolute value
  • num - any number

Examples

Example of Use

ABS() turns a negative number into a positive number.

pnum = ABS ( -4 )

After the code in this example is run, pnum will contain the number 4, the positive of -4.

Positive Number

If the number given to ABS() as an argument is already positive, it just returns the number as it is.

pnum = ABS ( 43 )

After the code in this example is executed, pnum will contain the number 43. ABS() will not turn a positive number into a negative number. To learn how to do this, see below.

Checking if a Number is Positive or Negative

Because ABS() only turns negative numbers into positive numbers and not vice versa, you can use it to check if a number is negative or positive.

IF numb = ABS(numb) THEN
    ' numb is positive
ELSE
    ' numb is negative
END IF

Making a Positive Number Negative

You use ABS() to check if a number is positive and then turn it into negative number.

IF numb = ABS(numb) THEN numb = numb * -1

You don't need to know how the math in this example works. However, if you are interested, 1 is the identity element of multiplication. Whenever you multiply a number by 1, you get the same number. When you multiply a number -1, you get the same number, just reversed in positive/negative value.

Related Pages

Categories: Uncategorized Pages
page_revision: 6, last_edited: 1237714504|%e %b %Y, %H:%M %Z (%O ago)