abs.js (1578B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2020 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var Float32Array = require( '@stdlib/array/float32' ); 24 var Uint32Array = require( '@stdlib/array/uint32' ); 25 26 27 // VARIABLES // 28 29 var FLOAT32_VIEW = new Float32Array( 1 ); 30 var UINT32_VIEW = new Uint32Array( FLOAT32_VIEW.buffer ); 31 32 // 0x7fffffff = 2147483647 => 0 11111111111 11111111111111111111 33 var ABS_MASK = 0x7fffffff>>>0; // asm type annotation 34 35 36 // MAIN // 37 38 /** 39 * Computes the absolute value of a single-precision floating-point number `x`. 40 * 41 * @param {number} x - input value 42 * @returns {number} absolute value 43 * 44 * @example 45 * var v = absf( -1.0 ); 46 * // returns 1.0 47 * 48 * @example 49 * var v = absf( 2.0 ); 50 * // returns 2.0 51 * 52 * @example 53 * var v = absf( 0.0 ); 54 * // returns 0.0 55 * 56 * @example 57 * var v = absf( -0.0 ); 58 * // returns 0.0 59 * 60 * @example 61 * var v = absf( NaN ); 62 * // returns NaN 63 */ 64 function absf( x ) { 65 FLOAT32_VIEW[ 0 ] = x; 66 UINT32_VIEW[ 0 ] &= ABS_MASK; 67 return FLOAT32_VIEW[ 0 ]; 68 } 69 70 71 // EXPORTS // 72 73 module.exports = absf;