Absolute Value

Compute an absolute value of a signed 32-bit integer.

The absolute value is defined as

StartAbsoluteValue x EndAbsoluteValue equals StartLayout Enlarged left-brace 1st Row 1st Column x 2nd Column if x greater-than-or-equal-to 0 2nd Row 1st Column negative x 2nd Column if x less-than 0 EndLayout

Usage

var absInt32 = require( '@stdlib/math/base/special/int32-abs' );

absInt32( x )

Computes an absolute value of a signed 32-bit integer.

var v = absInt32( -1|0 );
// returns 1

v = absInt32( 2|0 );
// returns 2

v = absInt32( 0|0 );
// returns 0

Notes

  • The implementation assumes two's complement.

  • In two's complement systems, the absolute value of the minimum signed 32-bit integer is out-of-range. The absolute value for the minimum signed 32-bit integer is thus undefined.

    // -2^31
    var x = -2147483648|0;
    
    var v = absInt32( x );
    // returns -2147483648
    

Examples

var randu = require( '@stdlib/random/base/randu' );
var round = require( '@stdlib/math/base/special/round' );
var absInt32 = require( '@stdlib/math/base/special/int32-abs' );

var x;
var i;

for ( i = 0; i < 100; i++ ) {
    x = round( randu() * 100.0 ) - 50;
    console.log( 'abs(%d) = %d', x, absInt32( x|0 ) );
}