cinv.js (2117B)
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 29 30 // VARIABLES // 31 32 var LARGE_THRESHOLD = FLOAT64_BIGGEST * 0.5; 33 var SMALL_THRESHOLD = FLOAT64_SMALLEST * ( 2.0 / EPS ); 34 var RECIP_EPS_SQR = 2.0 / ( EPS * EPS ); 35 36 37 // MAIN // 38 39 /** 40 * Computes the inverse of a complex number. 41 * 42 * @private 43 * @param {(Array|TypedArray|Object)} out - output array 44 * @param {number} re - real component 45 * @param {number} im - imaginary component 46 * @returns {(Array|TypedArray|Object)} output array 47 * 48 * @example 49 * var out = new Array( 2 ); 50 * 51 * var v = cinv( out, 2.0, 4.0 ); 52 * // returns [ 0.1, -0.2 ] 53 * 54 * var bool = ( v === out ); 55 * // returns true 56 */ 57 function cinv( out, re, im ) { 58 var ab; 59 var s; 60 var r; 61 var t; 62 63 ab = max( abs(re), abs(im) ); 64 s = 1.0; 65 if ( ab >= LARGE_THRESHOLD ) { 66 re *= 0.5; 67 im *= 0.5; 68 s *= 0.5; 69 } else if ( ab <= SMALL_THRESHOLD ) { 70 re *= RECIP_EPS_SQR; 71 im *= RECIP_EPS_SQR; 72 s *= RECIP_EPS_SQR; 73 } 74 if ( abs( im ) <= abs( re ) ) { 75 r = im / re; 76 t = 1.0 / ( re + (im*r) ); 77 out[ 0 ] = t; 78 out[ 1 ] = -r * t; 79 } else { 80 r = re / im; 81 t = 1.0 / ( im + (re*r) ); 82 out[ 0 ] = r * t; 83 out[ 1 ] = -t; 84 } 85 out[ 0 ] *= s; 86 out[ 1 ] *= s; 87 return out; 88 } 89 90 91 // EXPORTS // 92 93 module.exports = cinv;