time-to-botec

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

clampf.c (1690B)


      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/clampf.h"
     20 #include "stdlib/math/base/assert/is_nanf.h"
     21 #include "stdlib/math/base/assert/is_negative_zerof.h"
     22 
     23 /**
     24 * Restricts a single-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 * float y = stdlib_base_clampf( 3.14f, 0.0f, 5.0f );
     33 * // returns 3.14f
     34 *
     35 * @example
     36 * float y = stdlib_base_clampf( -3.14f, 0.0f, 5.0f );
     37 * // returns 0.0f
     38 */
     39 float stdlib_base_clampf( const float v, const float min, const float max ) {
     40 	if (
     41 		stdlib_base_is_nanf( v ) ||
     42 		stdlib_base_is_nanf( min ) ||
     43 		stdlib_base_is_nanf( max )
     44 	) {
     45 		return 0.0f / 0.0f; // 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.0f && stdlib_base_is_negative_zerof( v ) ) {
     56 		return min; // +-0.0
     57 	}
     58 	if ( v == 0.0f && stdlib_base_is_negative_zerof( max ) ) {
     59 		return max; // -0.0
     60 	}
     61 	// Case: min <= v <= max
     62 	return v;
     63 }