hypotf.c (1569B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2020 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/hypotf.h" 20 #include "stdlib/math/base/assert/is_nanf.h" 21 #include "stdlib/math/base/assert/is_infinitef.h" 22 #include "stdlib/math/base/special/sqrtf.h" 23 #include <math.h> 24 25 /** 26 * Computes the hypotenuse avoiding overflow and underflow (single-precision). 27 * 28 * @param x number 29 * @param y number 30 * @return hypotenuse 31 * 32 * @example 33 * float h = stdlib_base_hypotf( 5.0f, 12.0f ); 34 * // returns 13.0 35 */ 36 float stdlib_base_hypotf( const float x, const float y ) { 37 float tmp; 38 float a; 39 float b; 40 if ( stdlib_base_is_nanf( x ) || stdlib_base_is_nanf( y ) ) { 41 return 0.0f / 0.0f; // NaN 42 } 43 if ( stdlib_base_is_infinitef( x ) || stdlib_base_is_infinitef( y ) ) { 44 return INFINITY; 45 } 46 a = x; 47 b = y; 48 if ( a < 0.0f ) { 49 a = -a; 50 } 51 if ( b < 0.0f ) { 52 b = -b; 53 } 54 if ( a < b ) { 55 tmp = b; 56 b = a; 57 a = tmp; 58 } 59 if ( a == 0.0f ) { 60 return 0.0f; 61 } 62 b /= a; 63 return a * stdlib_base_sqrtf( 1.0f + (b*b) ); 64 }