copysign.js (2368B)
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 toWords = require( '@stdlib/number/float64/base/to-words' ); 24 var getHighWord = require( '@stdlib/number/float64/base/get-high-word' ); 25 var fromWords = require( '@stdlib/number/float64/base/from-words' ); 26 27 28 // VARIABLES // 29 30 // 10000000000000000000000000000000 => 2147483648 => 0x80000000 31 var SIGN_MASK = 0x80000000>>>0; // asm type annotation 32 33 // 01111111111111111111111111111111 => 2147483647 => 0x7fffffff 34 var MAGNITUDE_MASK = 0x7fffffff|0; // asm type annotation 35 36 // High/low words workspace: 37 var WORDS = [ 0, 0 ]; // WARNING: not thread safe 38 39 40 // MAIN // 41 42 /** 43 * Returns a double-precision floating-point number with the magnitude of `x` and the sign of `y`. 44 * 45 * @param {number} x - number from which to derive a magnitude 46 * @param {number} y - number from which to derive a sign 47 * @returns {number} a double-precision floating-point number 48 * 49 * @example 50 * var z = copysign( -3.14, 10.0 ); 51 * // returns 3.14 52 * 53 * @example 54 * var z = copysign( 3.14, -1.0 ); 55 * // returns -3.14 56 * 57 * @example 58 * var z = copysign( 1.0, -0.0 ); 59 * // returns -1.0 60 * 61 * @example 62 * var z = copysign( -3.14, -0.0 ); 63 * // returns -3.14 64 * 65 * @example 66 * var z = copysign( -0.0, 1.0 ); 67 * // returns 0.0 68 */ 69 function copysign( x, y ) { 70 var hx; 71 var hy; 72 73 // Split `x` into higher and lower order words: 74 toWords( WORDS, x ); 75 hx = WORDS[ 0 ]; 76 77 // Turn off the sign bit of `x`: 78 hx &= MAGNITUDE_MASK; 79 80 // Extract the higher order word from `y`: 81 hy = getHighWord( y ); 82 83 // Leave only the sign bit of `y` turned on: 84 hy &= SIGN_MASK; 85 86 // Copy the sign bit of `y` to `x`: 87 hx |= hy; 88 89 // Return a new value having the same magnitude as `x`, but with the sign of `y`: 90 return fromWords( hx, WORDS[ 1 ] ); 91 } 92 93 94 // EXPORTS // 95 96 module.exports = copysign;