cdiv.js (2435B)
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 abs = require( './../../../../base/special/abs' ); 24 var max = require( './../../../../base/special/max' ); 25 var FLOAT64_BIGGEST = require( '@stdlib/constants/float64/max' ); 26 var FLOAT64_SMALLEST = require( '@stdlib/constants/float64/smallest-normal' ); 27 var EPS = require( '@stdlib/constants/float64/eps' ); 28 var robustInternal = require( './robust_internal.js' ); 29 30 31 // VARIABLES // 32 33 var LARGE_THRESHOLD = FLOAT64_BIGGEST * 0.5; 34 var SMALL_THRESHOLD = FLOAT64_SMALLEST * ( 2.0 / EPS ); 35 var RECIP_EPS_SQR = 2.0 / ( EPS * EPS ); 36 37 38 // MAIN // 39 40 /** 41 * Divides two complex numbers. 42 * 43 * @private 44 * @param {(Array|TypedArray|Object)} out - output array 45 * @param {number} re1 - real component 46 * @param {number} im1 - imaginary component 47 * @param {number} re2 - real component 48 * @param {number} im2 - imaginary component 49 * @returns {(Array|TypedArray|Object)} output array 50 * 51 * @example 52 * var out = new Array( 2 ); 53 * 54 * var v = cdiv( out, -13.0, -1.0, -2.0, 1.0 ); 55 * // returns [ 5.0, 3.0 ] 56 * 57 * var bool = ( v === out ); 58 * // returns true 59 */ 60 function cdiv( out, re1, im1, re2, im2 ) { 61 var ab; 62 var cd; 63 var s; 64 65 ab = max( abs(re1), abs(im1) ); 66 cd = max( abs(re2), abs(im2) ); 67 s = 1.0; 68 69 if ( ab >= LARGE_THRESHOLD ) { 70 re1 *= 0.5; 71 im1 *= 0.5; 72 s *= 2.0; 73 } else if ( ab <= SMALL_THRESHOLD ) { 74 re1 *= RECIP_EPS_SQR; 75 im1 *= RECIP_EPS_SQR; 76 s /= RECIP_EPS_SQR; 77 } 78 if ( cd >= LARGE_THRESHOLD ) { 79 re2 *= 0.5; 80 im2 *= 0.5; 81 s *= 0.5; 82 } else if ( cd <= SMALL_THRESHOLD ) { 83 re2 *= RECIP_EPS_SQR; 84 im2 *= RECIP_EPS_SQR; 85 s *= RECIP_EPS_SQR; 86 } 87 if ( abs( im2 ) <= abs( re2 ) ) { 88 robustInternal( out, re1, im1, re2, im2 ); 89 } else { 90 robustInternal( out, im1, re1, im2, re2 ); 91 out[ 1 ] *= -1; 92 } 93 out[ 0 ] *= s; 94 out[ 1 ] *= s; 95 return out; 96 } 97 98 99 // EXPORTS // 100 101 module.exports = cdiv;