1/* 2 * Copyright (C) 2016 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package androidx.core.math; 18 19/** 20 * A utility class providing functions useful for common mathematical operations. 21 */ 22public class MathUtils { 23 24 private MathUtils() {} 25 26 /** 27 * This method takes a numerical value and ensures it fits in a given numerical range. If the 28 * number is smaller than the minimum required by the range, then the minimum of the range will 29 * be returned. If the number is higher than the maximum allowed by the range then the maximum 30 * of the range will be returned. 31 * 32 * @param value the value to be clamped. 33 * @param min minimum resulting value. 34 * @param max maximum resulting value. 35 * 36 * @return the clamped value. 37 */ 38 public static float clamp(float value, float min, float max) { 39 if (value < min) { 40 return min; 41 } else if (value > max) { 42 return max; 43 } 44 return value; 45 } 46 47 /** 48 * This method takes a numerical value and ensures it fits in a given numerical range. If the 49 * number is smaller than the minimum required by the range, then the minimum of the range will 50 * be returned. If the number is higher than the maximum allowed by the range then the maximum 51 * of the range will be returned. 52 * 53 * @param value the value to be clamped. 54 * @param min minimum resulting value. 55 * @param max maximum resulting value. 56 * 57 * @return the clamped value. 58 */ 59 public static double clamp(double value, double min, double max) { 60 if (value < min) { 61 return min; 62 } else if (value > max) { 63 return max; 64 } 65 return value; 66 } 67 68 /** 69 * This method takes a numerical value and ensures it fits in a given numerical range. If the 70 * number is smaller than the minimum required by the range, then the minimum of the range will 71 * be returned. If the number is higher than the maximum allowed by the range then the maximum 72 * of the range will be returned. 73 * 74 * @param value the value to be clamped. 75 * @param min minimum resulting value. 76 * @param max maximum resulting value. 77 * 78 * @return the clamped value. 79 */ 80 public static int clamp(int value, int min, int max) { 81 if (value < min) { 82 return min; 83 } else if (value > max) { 84 return max; 85 } 86 return value; 87 } 88} 89