abs.js (2753B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 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 Float64Array = require( '@stdlib/array/float64' ); 24 var Uint32Array = require( '@stdlib/array/uint32' ); 25 var HIGH = require( './high.js' ); 26 27 28 // VARIABLES // 29 30 var FLOAT64_VIEW = new Float64Array( 1 ); 31 var UINT32_VIEW = new Uint32Array( FLOAT64_VIEW.buffer ); 32 33 // 0x7fffffff = 2147483647 => 0 11111111111 11111111111111111111 34 var ABS_MASK = 0x7fffffff>>>0; // asm type annotation 35 36 37 // MAIN // 38 39 /** 40 * Computes the absolute value of a double-precision floating-point number `x`. 41 * 42 * ## Notes 43 * 44 * ```text 45 * float64 (64 bits) 46 * f := fraction (significand/mantissa) (52 bits) 47 * e := exponent (11 bits) 48 * s := sign bit (1 bit) 49 * 50 * |-------- -------- -------- -------- -------- -------- -------- --------| 51 * | Float64 | 52 * |-------- -------- -------- -------- -------- -------- -------- --------| 53 * | Uint32 | Uint32 | 54 * |-------- -------- -------- -------- -------- -------- -------- --------| 55 * ``` 56 * 57 * If little endian (more significant bits last): 58 * 59 * ```text 60 * <-- lower higher --> 61 * | f7 f6 f5 f4 f3 f2 e2 | f1 |s| e1 | 62 * ``` 63 * 64 * If big endian (more significant bits first): 65 * 66 * ```text 67 * <-- higher lower --> 68 * |s| e1 e2 | f1 f2 f3 f4 f5 f6 f7 | 69 * ``` 70 * 71 * In which Uint32 can we find the higher order bits? If little endian, the second; if big endian, the first. 72 * 73 * 74 * ## References 75 * 76 * - [Open Group][1] 77 * 78 * [1]: http://pubs.opengroup.org/onlinepubs/9629399/chap14.htm 79 * 80 * @param {number} x - input value 81 * @returns {number} absolute value 82 * 83 * @example 84 * var v = abs( -1.0 ); 85 * // returns 1.0 86 * 87 * @example 88 * var v = abs( 2.0 ); 89 * // returns 2.0 90 * 91 * @example 92 * var v = abs( 0.0 ); 93 * // returns 0.0 94 * 95 * @example 96 * var v = abs( -0.0 ); 97 * // returns 0.0 98 * 99 * @example 100 * var v = abs( NaN ); 101 * // returns NaN 102 */ 103 function abs( x ) { 104 FLOAT64_VIEW[ 0 ] = x; 105 UINT32_VIEW[ HIGH ] &= ABS_MASK; 106 return FLOAT64_VIEW[ 0 ]; 107 } 108 109 110 // EXPORTS // 111 112 module.exports = abs;