001/******************************************************************************* 002 * This software is provided as a supplement to the authors' textbooks on digital 003 * image processing published by Springer-Verlag in various languages and editions. 004 * Permission to use and distribute this software is granted under the BSD 2-Clause 005 * "Simplified" License (see http://opensource.org/licenses/BSD-2-Clause). 006 * Copyright (c) 2006-2016 Wilhelm Burger, Mark J. Burge. All rights reserved. 007 * Visit http://imagingbook.com for additional details. 008 *******************************************************************************/ 009 010package imagingbook.lib.math; 011 012public abstract class Arithmetic { 013 014 // machine accuracy for IEEE 754 float/double; 015 public static final float EPSILON_FLOAT = 1e-7f; // 1.19 x 10^-7 016 public static final double EPSILON_DOUBLE = 2e-16; // 2.22 x 10^-16 017 018 public static int sqr(int x) { 019 return x * x; 020 } 021 022 public static float sqr(float x) { 023 return x * x; 024 } 025 026 public static double sqr(double x) { 027 return x * x; 028 } 029 030 /** 031 * Integer version of modulus operator (as described in the book). 032 * Calculates {@code a mod b}. 033 * * Also see <a href="http://en.wikipedia.org/wiki/Modulo_operation">here</a>. 034 * @param a dividend 035 * @param b divisor 036 * @return {@code a mod b} 037 */ 038 public static int mod(int a, int b) { 039 if (b == 0) 040 return a; 041 if (a * b >= 0) // a, b are either both positive or negative 042 return a - b * (a / b); 043 else 044 return a - b * (a / b - 1); 045// return Math.floorMod(a, a); // equivalent, but requires Java 1.8 046 } 047 048 /** 049 * Non-integer version of modulus operator, with results identical to Mathematica. 050 * Calulates {@code a mod b}. 051 * Also see <a href="http://en.wikipedia.org/wiki/Modulo_operation">here</a>. 052 * @param a dividend 053 * @param b divisor 054 * @return {@code a mod b} 055 */ 056 public static double mod(double a, double b) { 057 return a - b * Math.floor(a / b); 058 } 059 060 /** 061 * Test for zero (float version). 062 * @param x quantity to be tested 063 * @return true if argument is close to zero 064 */ 065 public static boolean isZero(float x) { 066 return Math.abs(x) < Arithmetic.EPSILON_FLOAT; 067 } 068 069 /** 070 * Test for zero (double version). 071 * @param x quantity to be tested 072 * @return true if argument is close to zero 073 */ 074 public static boolean isZero(double x) { 075 return Math.abs(x) < Arithmetic.EPSILON_DOUBLE; 076 } 077 078}