time-to-botec

Benchmark sampling in different programming languages
Log | Files | Refs | README

hypot.c (1537B)


      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 #include "stdlib/math/base/special/hypot.h"
     20 #include "stdlib/math/base/assert/is_nan.h"
     21 #include "stdlib/math/base/assert/is_infinite.h"
     22 #include "stdlib/math/base/special/sqrt.h"
     23 #include <math.h>
     24 
     25 /**
     26 * Computes the hypotenuse avoiding overflow and underflow.
     27 *
     28 * @param x       number
     29 * @param y       number
     30 * @return        hypotenuse
     31 *
     32 * @example
     33 * double h = stdlib_base_hypot( 5.0, 12.0 );
     34 * // returns 13.0
     35 */
     36 double stdlib_base_hypot( const double x, const double y ) {
     37 	double tmp;
     38 	double a;
     39 	double b;
     40 	if ( stdlib_base_is_nan( x ) || stdlib_base_is_nan( y ) ) {
     41 		return 0.0 / 0.0; // NaN
     42 	}
     43 	if ( stdlib_base_is_infinite( x ) || stdlib_base_is_infinite( y ) ) {
     44 		return HUGE_VAL;
     45 	}
     46 	a = x;
     47 	b = y;
     48 	if ( a < 0.0 ) {
     49 		a = -a;
     50 	}
     51 	if ( b < 0.0 ) {
     52 		b = -b;
     53 	}
     54 	if ( a < b ) {
     55 		tmp = b;
     56 		b = a;
     57 		a = tmp;
     58 	}
     59 	if ( a == 0.0 ) {
     60 		return 0.0;
     61 	}
     62 	b /= a;
     63 	return a * stdlib_base_sqrt( 1.0 + (b*b) );
     64 }