clamp.c (1673B)
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/clamp.h" 20 #include "stdlib/math/base/assert/is_nan.h" 21 #include "stdlib/math/base/assert/is_negative_zero.h" 22 23 /** 24 * Restricts a double-precision floating-point number to a specified range. 25 * 26 * @param v number 27 * @param min minimum value 28 * @param max maximum value 29 * @return restricted value 30 * 31 * @example 32 * double y = stdlib_base_clamp( 3.14, 0.0, 5.0 ); 33 * // returns 3.14 34 * 35 * @example 36 * double y = stdlib_base_clamp( -3.14, 0.0, 5.0 ); 37 * // returns 0.0 38 */ 39 double stdlib_base_clamp( const double v, const double min, const double max ) { 40 if ( 41 stdlib_base_is_nan( v ) || 42 stdlib_base_is_nan( min ) || 43 stdlib_base_is_nan( max ) 44 ) { 45 return 0.0 / 0.0; // NaN 46 } 47 // Simple cases... 48 if ( v < min ) { 49 return min; 50 } 51 if ( v > max ) { 52 return max; 53 } 54 // Special cases for handling +-0.0... 55 if ( min == 0.0 && stdlib_base_is_negative_zero( v ) ) { 56 return min; // +-0.0 57 } 58 if ( v == 0.0 && stdlib_base_is_negative_zero( max ) ) { 59 return max; // -0.0 60 } 61 // Case: min <= v <= max 62 return v; 63 }