Java Tutorial/Development/Math Functions — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Версия 17:44, 31 мая 2010
Содержание
- 1 Calculate the floor of the log, base 2
- 2 Demonstrate toDegrees() and toRadians().
- 3 Find absolute value of float, int, double and long using Math.abs
- 4 Find ceiling value of a number using Math.ceil
- 5 Find exponential value of a number using Math.exp
- 6 Find floor value of a number using Math.floor
- 7 Find maximum of two numbers using Math.max
- 8 Find natural logarithm value of a number using Math.log
- 9 Find power using Math.pow
- 10 Find square root of a number using Math.sqrt
- 11 Floating Point Number Enhancements in JDK 6
- 12 Greatest Common Divisor (GCD) of positive integer numbers
- 13 Least Common Multiple (LCM) of two strictly positive integer numbers
- 14 Math Class Methods
- 15 Math.copySign
- 16 Math.getExponent
- 17 Math.min
- 18 Math.nextAfter
- 19 Math.nextUp
- 20 Math.scalb
- 21 Moving Average
- 22 Normalize an angle in a 2&pi wide interval around a center value.
- 23 Normalizes an angle to an absolute angle.
- 24 Normalizes an angle to a relative angle.
- 25 Normalizes an angle to be near an absolute angle
- 26 Returns n!. Shorthand for n Factorial, the product of the numbers 1,...,n.
- 27 Returns n!. Shorthand for n Factorial, the product of the numbers 1,...,n as a double.
- 28 Returns the hyperbolic cosine of x.
- 29 Returns the hyperbolic sine of x.
- 30 Returns the natural logarithm of n!.
- 31 Returns the natural log of the (http://mathworld.wolfram.com/BinomialCoefficient.html) Binomial Coefficient
- 32 Round Java float and double numbers using Math.round
- 33 Round the given value to the specified number of decimal places. The value is rounded using the BigDecimal.ROUND_HALF_UP method.
- 34 sqrt(a^2 + b^2) without under/overflow
- 35 Testing the Math class methods
- 36 Use math functions
- 37 Value is rounded using the given method which is any method defined in BigDecimal
Calculate the floor of the log, base 2
/*
* $RCSfile: MathUtil.java,v $
* $Revision: 1.1 $
* $Date: 2005/02/11 05:02:25 $
* $State: Exp $
*
* Class: MathUtil
*
* Description: Utility mathematical methods
*
*
*
* COPYRIGHT:
*
* This software module was originally developed by Raphaël Grosbois and
* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel
* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David
* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research
* Centre France S.A) in the course of development of the JPEG2000
* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This
* software module is an implementation of a part of the JPEG 2000
* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio
* Systems AB and Canon Research Centre France S.A (collectively JJ2000
* Partners) agree not to assert against ISO/IEC and users of the JPEG
* 2000 Standard (Users) any of their rights under the copyright, not
* including other intellectual property rights, for this software module
* with respect to the usage by ISO/IEC and Users of this software module
* or modifications thereof for use in hardware or software products
* claiming conformance to the JPEG 2000 Standard. Those intending to use
* this software module in hardware or software products are advised that
* their use may infringe existing patents. The original developers of
* this software module, JJ2000 Partners and ISO/IEC assume no liability
* for use of this software module or modifications thereof. No license
* or right to this software module is granted for non JPEG 2000 Standard
* conforming products. JJ2000 Partners have full right to use this
* software module for his/her own purpose, assign or donate this
* software module to any third party and to inhibit third parties from
* using this software module for non JPEG 2000 Standard conforming
* products. This copyright notice must be included in all copies or
* derivative works of this software module.
*
* Copyright (c) 1999/2000 JJ2000 Partners.
* */
/**
* This class contains a collection of utility methods fro mathematical
* operations. All methods are static.
* */
public class MathUtil {
/**
* Method that calculates the floor of the log, base 2,
* of "x". The calculation is performed in integer arithmetic,
* therefore, it is exact.
*
* @param x The value to calculate log2 on.
*
* @return floor(log(x)/log(2)), calculated in an exact way.
* */
public static int log2(int x) {
int y,v;
// No log of 0 or negative
if (x <= 0) {
throw new IllegalArgumentException(""+x+" <= 0");
}
// Calculate log2 (it"s actually floor log2)
v = x;
y = -1;
while (v>0) {
v >>=1;
y++;
}
return y;
}
}
Demonstrate toDegrees() and toRadians().
class Angles {
public static void main(String args[]) {
double theta = 120.0;
System.out.println(theta + " degrees is " + Math.toRadians(theta) + " radians.");
theta = 1.312;
System.out.println(theta + " radians is " + Math.toDegrees(theta) + " degrees.");
}
}
Find absolute value of float, int, double and long using Math.abs
public class Main {
public static void main(String[] args) {
int i = 8;
int j = -5;
System.out.println("Absolute value of " + i + " is :" + Math.abs(i));
System.out.println("Absolute value of " + j + " is :" + Math.abs(j));
float f1 = 1.40f;
float f2 = -5.28f;
System.out.println("Absolute value of " + f1 + " is :" + Math.abs(f1));
System.out.println("Absolute value of " + f2 + " is :" + Math.abs(f2));
double d1 = 3.324;
double d2 = -9.324;
System.out.println("Absolute value of " + d1 + " is :" + Math.abs(d1));
System.out.println("Absolute value of " + d2 + " is :" + Math.abs(d2));
long l1 = 3L;
long l2 = -4L;
System.out.println("Absolute value of " + l1 + " is :" + Math.abs(l1));
System.out.println("Absolute value of " + l2 + " is :" + Math.abs(l2));
}
}
Find ceiling value of a number using Math.ceil
public class Main {
public static void main(String[] args) {
System.out.println(Math.ceil(10));
System.out.println(Math.ceil(9.1));
System.out.println(Math.ceil(5.5));
System.out.println(Math.ceil(-10));
System.out.println(Math.ceil(-4.4));
System.out.println(Math.ceil(0));
}
}
/*
10.0
10.0
6.0
-10.0
-4.0
0.0
*/
Find exponential value of a number using Math.exp
public class Main {
public static void main(String[] args) {
System.out.println("Exponential of 2 is : " + Math.exp(2));
}
}
Find floor value of a number using Math.floor
public class Main {
public static void main(String[] args) {
System.out.println(Math.floor(31.1));
}
}
Find maximum of two numbers using Math.max
public class Main {
public static void main(String[] args) {
System.out.println(Math.max(2, 4));
System.out.println(Math.max(1.4f, 1.3f));
System.out.println(Math.max(1.34, 1.45));
System.out.println(Math.max(1l, 5l));
}
}
Find natural logarithm value of a number using Math.log
public class Main {
public static void main(String[] args) {
System.out.println("Natural logarithm value of 2 is : " + Math.log(2));
}
}
//Natural logarithm value of 2 is : 0.6931471805599453
Find power using Math.pow
public class Main {
public static void main(String[] args) {
// returns 2 raised to 2, i.e. 4
System.out.println(Math.pow(2, 2));
// returns -3 raised to 2, i.e. 9
System.out.println(Math.pow(-3, 2));
}
}
Find square root of a number using Math.sqrt
public class Main {
public static void main(String[] args) {
// returns square root of 9, i.e. 3
System.out.println(Math.sqrt(9));
// returns square root of 25.5
System.out.println(Math.sqrt(25.5));
}
}
Floating Point Number Enhancements in JDK 6
The java.lang.Math class in Java 6 has also been enhanced with the following new methods:
public static int getExponent (float f)
public static double copySign (double magnitude, double sign)
public static float copySign (float magnitude, float sign)
public static double nextAfter (double start, double direction)
public static double nextUp (double d)
public static double scalb (double d, int scaleFactor)
Greatest Common Divisor (GCD) of positive integer numbers
/*
* $RCSfile: MathUtil.java,v $
* $Revision: 1.1 $
* $Date: 2005/02/11 05:02:25 $
* $State: Exp $
*
* Class: MathUtil
*
* Description: Utility mathematical methods
*
*
*
* COPYRIGHT:
*
* This software module was originally developed by Raphaël Grosbois and
* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel
* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David
* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research
* Centre France S.A) in the course of development of the JPEG2000
* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This
* software module is an implementation of a part of the JPEG 2000
* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio
* Systems AB and Canon Research Centre France S.A (collectively JJ2000
* Partners) agree not to assert against ISO/IEC and users of the JPEG
* 2000 Standard (Users) any of their rights under the copyright, not
* including other intellectual property rights, for this software module
* with respect to the usage by ISO/IEC and Users of this software module
* or modifications thereof for use in hardware or software products
* claiming conformance to the JPEG 2000 Standard. Those intending to use
* this software module in hardware or software products are advised that
* their use may infringe existing patents. The original developers of
* this software module, JJ2000 Partners and ISO/IEC assume no liability
* for use of this software module or modifications thereof. No license
* or right to this software module is granted for non JPEG 2000 Standard
* conforming products. JJ2000 Partners have full right to use this
* software module for his/her own purpose, assign or donate this
* software module to any third party and to inhibit third parties from
* using this software module for non JPEG 2000 Standard conforming
* products. This copyright notice must be included in all copies or
* derivative works of this software module.
*
* Copyright (c) 1999/2000 JJ2000 Partners.
* */
/**
* This class contains a collection of utility methods fro mathematical
* operations. All methods are static.
* */
public class MathUtil {
/**
* Method that calculates the Greatest Common Divisor (GCD) of several
* positive integer numbers.
*
* @param x Array containing the numbers.
* */
public static final int gcd(int[] x) {
if(x.length<2) {
throw new Error("Do not use this method if there are less than"+
" two numbers.");
}
int tmp = gcd(x[x.length-1],x[x.length-2]);
for(int i=x.length-3; i>=0; i--) {
if(x[i]<0) {
throw new IllegalArgumentException("Cannot compute the least "+
"common multiple of "+
"several numbers where "+
"one, at least,"+
"is negative.");
}
tmp = gcd(tmp,x[i]);
}
return tmp;
}
/**
* Method that calculates the Greatest Common Divisor (GCD) of two
* positive integer numbers.
* */
public static final int gcd(int x1,int x2) {
if(x1<0 || x2<0) {
throw new IllegalArgumentException("Cannot compute the GCD "+
"if one integer is negative.");
}
int a,b,g,z;
if(x1>x2) {
a = x1;
b = x2;
} else {
a = x2;
b = x1;
}
if(b==0) return 0;
g = b;
while (g!=0) {
z= a%g;
a = g;
g = z;
}
return a;
}
}
Least Common Multiple (LCM) of two strictly positive integer numbers
/*
* $RCSfile: MathUtil.java,v $
* $Revision: 1.1 $
* $Date: 2005/02/11 05:02:25 $
* $State: Exp $
*
* Class: MathUtil
*
* Description: Utility mathematical methods
*
*
*
* COPYRIGHT:
*
* This software module was originally developed by Raphaël Grosbois and
* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel
* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David
* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research
* Centre France S.A) in the course of development of the JPEG2000
* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This
* software module is an implementation of a part of the JPEG 2000
* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio
* Systems AB and Canon Research Centre France S.A (collectively JJ2000
* Partners) agree not to assert against ISO/IEC and users of the JPEG
* 2000 Standard (Users) any of their rights under the copyright, not
* including other intellectual property rights, for this software module
* with respect to the usage by ISO/IEC and Users of this software module
* or modifications thereof for use in hardware or software products
* claiming conformance to the JPEG 2000 Standard. Those intending to use
* this software module in hardware or software products are advised that
* their use may infringe existing patents. The original developers of
* this software module, JJ2000 Partners and ISO/IEC assume no liability
* for use of this software module or modifications thereof. No license
* or right to this software module is granted for non JPEG 2000 Standard
* conforming products. JJ2000 Partners have full right to use this
* software module for his/her own purpose, assign or donate this
* software module to any third party and to inhibit third parties from
* using this software module for non JPEG 2000 Standard conforming
* products. This copyright notice must be included in all copies or
* derivative works of this software module.
*
* Copyright (c) 1999/2000 JJ2000 Partners.
* */
/**
* This class contains a collection of utility methods fro mathematical
* operations. All methods are static.
* */
public class MathUtil {
/**
* Method that calculates the Least Common Multiple (LCM) of two strictly
* positive integer numbers.
*
* @param x1 First number
*
* @param x2 Second number
* */
public static final int lcm(int x1,int x2) {
if(x1<=0 || x2<=0) {
throw new IllegalArgumentException("Cannot compute the least "+
"common multiple of two "+
"numbers if one, at least,"+
"is negative.");
}
int max,min;
if (x1>x2) {
max = x1;
min = x2;
} else {
max = x2;
min = x1;
}
for(int i=1; i<=min; i++) {
if( (max*i)%min == 0 ) {
return i*max;
}
}
throw new Error("Cannot find the least common multiple of numbers "+
x1+" and "+x2);
}
/**
* Method that calculates the Least Common Multiple (LCM) of several
* positive integer numbers.
*
* @param x Array containing the numbers.
* */
public static final int lcm(int[] x) {
if(x.length<2) {
throw new Error("Do not use this method if there are less than"+
" two numbers.");
}
int tmp = lcm(x[x.length-1],x[x.length-2]);
for(int i=x.length-3; i>=0; i--) {
if(x[i]<=0) {
throw new IllegalArgumentException("Cannot compute the least "+
"common multiple of "+
"several numbers where "+
"one, at least,"+
"is negative.");
}
tmp = lcm(tmp,x[i]);
}
return tmp;
}
}
Math Class Methods
FunctionDescriptionIEEEremainder(double, double)Returns the remainder of f1 divided by f2 as defined by IEEE 754abs(int a)Returns the absolute integer value of aabs(long a)Returns the absolute long value of aabs(float a)Returns the absolute float value of aabs(double a)Returns the absolute double value of aacos(double a)Returns the arc cosine of a, in the range of 0.0 through piasin(double a)Returns the arc sine of a, in the range of -pi/2 through pi/2atan(double a)Returns the arc tangent of a, in the range of -pi/2 through pi/2atan2(double a, double b)Converts rectangular coordinates (a, b) to polar (r, theta)ceil(double a)Returns the "ceiling," or smallest whole number greater than or equal to acos(double)Returns the trigonometric cosine of an angleexp(double a)Returns the exponential number e(2.718...) raised to the power of afloor(double a)Returns the "floor," or largest whole number less than or equal to alog(double a)Returns the natural logarithm (base e) of amax(int a, int b)Takes two int values, a and b, and returns the greater of the twomax(long a, long b)Takes two long values, a and b, and returns the greater of the twomax(float a, float b)Takes two float values, a and b, and returns the greater of the twomax(double a, double b)Takes two double values, a and b, and returns the greater of the twomin(int a, int b)Takes two integer values, a and b, and returns the smaller of the twomin(long a, long b)Takes two long values, a and b, and returns the smaller of the twomin(float a, float b)Takes two float values, a and b, and returns the smaller of the twomin(double a, double b)Takes two double values, a and b, and returns the smaller of the twopow(double a, double b)Returns the number a raised to the power of brandom()Generates a random number between 0.0 and 1.0rint(double)Returns the closest integer to the argument, but as a floating-point numberround(float)Rounds off a float value by first adding 0.5 to it and then returning the largest integer that is less than or equal to this new valueround(double)Rounds off a double value by first adding 0.5 to it and then returning the largest integer that is less than or equal to this new valuesin(double)Returns the trigonometric sine of an anglesqrt(double)Returns the square root of atan(double)Returns the trigonometric tangent of an angletoDegrees(double)Translates radians to degreestoRadians(double)Translates degrees to radians
Math.copySign
public class FloastPointDemo {
public static void main(String[] args) {
// Returns a copySign of the first argument
double d = Math.copySign (1234.56, -1);
System.out.println ("Math.copySign (1234.56, -1) = " + d);
}
}
//
Math.copySign (1234.56, -1) = -1234.56
Math.getExponent
public class FloastPointDemo {
public static void main (String[] args) {
// Returns the unbiased exponent value of a double,
// where 2^exp <= d. In this case, 2^4 <= 17
int exp = Math.getExponent (17.0);
System.out.println ("Math.getExponent (17.0) = " + exp);
}
}
//
Math.getExponent (17.0) = 4
Math.min
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Sun Microsystems nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
public class MinDemo {
public static void main(String[] args) {
double enrollmentPrice = 45.875;
double closingPrice = 54.375;
System.out.println("Your purchase price is: $"
+ Math.min(enrollmentPrice, closingPrice));
}
}
Math.nextAfter
public class FloastPointDemo {
public static void main(String[] args) {
// Returns the lesser adjacent of a double
double lesserAdjacent = Math.nextAfter(123.0, 120.0);
System.out.println("Math.nextAfter (123.0, 120.0) = " + lesserAdjacent);
}
}
//
Math.nextAfter (123.0, 120.0) = 122.99999999999999
Math.nextUp
public class FloastPointDemo {
public static void main(String[] args) {
// Returns the greater adjacent of a double
double greaterAdjacent = Math.nextUp(123.0);
System.out.println("Math.nextUp (123.0) = " + greaterAdjacent);
}
}
//
Math.nextUp (123.0) = 123.00000000000001
Math.scalb
public class FloastPointDemo {
public static void main (String[] args) {
// Returns 12.0 x (2^3)
double scalbResult = Math.scalb (12.0, 3);
System.out.println ("Math.scalb (12.0, 3) = " + scalbResult);
}
}
Math.scalb (12.0, 3) = 96.0
Moving Average
/**********************************************************************
Copyright (c) 2007 Erik Bengtson and others. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
...
**********************************************************************/
import java.util.LinkedList;
/**
* Math Utilities.
*/
public class MathUtils
{
/**
* Simple Moving Average
*/
public static class SMA
{
private LinkedList values = new LinkedList();
private int length;
private double sum = 0;
private double average = 0;
/**
*
* @param length the maximum length
*/
public SMA(int length)
{
if (length <= 0)
{
throw new IllegalArgumentException("length must be greater than zero");
}
this.length = length;
}
public double currentAverage()
{
return average;
}
/**
* Compute the moving average.
* Synchronised so that no changes in the underlying data is made during calculation.
* @param value The value
* @return The average
*/
public synchronized double compute(double value)
{
if (values.size() == length && length > 0)
{
sum -= ((Double) values.getFirst()).doubleValue();
values.removeFirst();
}
sum += value;
values.addLast(new Double(value));
average = sum / values.size();
return average;
}
}
}
Normalize an angle in a 2&pi wide interval around a center value.
import java.io.File;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
public class Main {
/** 2 π. */
private static final double TWO_PI = 2 * Math.PI;
/**
* Normalize an angle in a 2&pi wide interval around a center value.
* This method has three main uses:
* <ul>
* <li>normalize an angle between 0 and 2π:<br/>
* <code>a = MathUtils.normalizeAngle(a, Math.PI);</code></li>
* <li>normalize an angle between -π and +π<br/>
* <code>a = MathUtils.normalizeAngle(a, 0.0);</code></li>
* <li>compute the angle between two defining angular positions:<br>
* <code>angle = MathUtils.normalizeAngle(end, start) - start;</code></li>
* </ul>
* Note that due to numerical accuracy and since π cannot be represented
* exactly, the result interval is <em>closed</em>, it cannot be half-closed
* as would be more satisfactory in a purely mathematical view.
* @param a angle to normalize
* @param center center of the desired 2π interval for the result
* @return a-2kπ with integer k and center-π <= a-2kπ <= center+π
* @since 1.2
*/
public static double normalizeAngle(double a, double center) {
return a - TWO_PI * Math.floor((a + Math.PI - center) / TWO_PI);
}
}
Normalizes an angle to an absolute angle.
/*******************************************************************************
* Copyright (c) 2001, 2008 Mathew A. Nelson and Robocode contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://robocode.sourceforge.net/license/cpl-v10.html
*
* Contributors:
* Mathew A. Nelson
* - Initial API and implementation
* Flemming N. Larsen
* - Moved all methods to classes like FileUtil, StringUtil, WindowUtil,
* Logger etc. exception for the following methods, which have been kept
* here as legacy robots make use of these methods:
* - normalAbsoluteAngle()
* - normalNearAbsoluteAngle()
* - normalRelativeAngle()
* - The isNear() was made public
* - Optimized and provided javadocs for all methods
*******************************************************************************/
import static java.lang.Math.PI;
import java.util.Random;
/**
* Utility class that provide methods for normalizing angles.
*
* @author Mathew A. Nelson (original)
* @author Flemming N. Larsen (contributor)
*/
public class Utils {
/**
* Normalizes an angle to an absolute angle.
* The normalized angle will be in the range from 0 to 360, where 360
* itself is not included.
*
* @param angle the angle to normalize
* @return the normalized angle that will be in the range of [0,360[
*/
public static double normalAbsoluteAngleDegrees(double angle) {
return (angle %= 360) >= 0 ? angle : (angle + 360);
}
}
Normalizes an angle to a relative angle.
/*******************************************************************************
* Copyright (c) 2001, 2008 Mathew A. Nelson and Robocode contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://robocode.sourceforge.net/license/cpl-v10.html
*
* Contributors:
* Mathew A. Nelson
* - Initial API and implementation
* Flemming N. Larsen
* - Moved all methods to classes like FileUtil, StringUtil, WindowUtil,
* Logger etc. exception for the following methods, which have been kept
* here as legacy robots make use of these methods:
* - normalAbsoluteAngle()
* - normalNearAbsoluteAngle()
* - normalRelativeAngle()
* - The isNear() was made public
* - Optimized and provided javadocs for all methods
*******************************************************************************/
import static java.lang.Math.PI;
import java.util.Random;
/**
* Utility class that provide methods for normalizing angles.
*
* @author Mathew A. Nelson (original)
* @author Flemming N. Larsen (contributor)
*/
public class Utils {
private final static double TWO_PI = 2 * PI;
/**
* Normalizes an angle to a relative angle.
* The normalized angle will be in the range from -PI to PI, where PI
* itself is not included.
*
* @param angle the angle to normalize
* @return the normalized angle that will be in the range of [-PI,PI[
*/
public static double normalRelativeAngle(double angle) {
return (angle %= TWO_PI) >= 0 ? (angle < PI) ? angle : angle - TWO_PI : (angle >= -PI) ? angle : angle + TWO_PI;
}
}
Normalizes an angle to be near an absolute angle
/*******************************************************************************
* Copyright (c) 2001, 2008 Mathew A. Nelson and Robocode contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://robocode.sourceforge.net/license/cpl-v10.html
*
* Contributors:
* Mathew A. Nelson
* - Initial API and implementation
* Flemming N. Larsen
* - Moved all methods to classes like FileUtil, StringUtil, WindowUtil,
* Logger etc. exception for the following methods, which have been kept
* here as legacy robots make use of these methods:
* - normalAbsoluteAngle()
* - normalNearAbsoluteAngle()
* - normalRelativeAngle()
* - The isNear() was made public
* - Optimized and provided javadocs for all methods
*******************************************************************************/
import static java.lang.Math.PI;
import java.util.Random;
/**
* Utility class that provide methods for normalizing angles.
*
* @author Mathew A. Nelson (original)
* @author Flemming N. Larsen (contributor)
*/
public class Utils {
private final static double TWO_PI = 2 * PI;
private final static double THREE_PI_OVER_TWO = 3 * PI / 2;
private final static double PI_OVER_TWO = PI / 2;
public static final double NEAR_DELTA = .00001;
/**
* Normalizes an angle to be near an absolute angle.
* The normalized angle will be in the range from 0 to 2*PI, where 2*PI
* itself is not included.
* If the normalized angle is near to 0, PI/2, PI, 3*PI/2 or 2*PI, that
* angle will be returned. The {@link #isNear(double, double) isNear}
* method is used for defining when the angle is near one of angles listed
* above.
*
* @param angle the angle to normalize
* @return the normalized angle that will be in the range of [0,2*PI[
* @see #normalAbsoluteAngle(double)
* @see #isNear(double, double)
*/
public static double normalNearAbsoluteAngle(double angle) {
angle = (angle %= TWO_PI) >= 0 ? angle : (angle + TWO_PI);
if (isNear(angle, PI)) {
return PI;
} else if (angle < PI) {
if (isNear(angle, 0)) {
return 0;
} else if (isNear(angle, PI_OVER_TWO)) {
return PI_OVER_TWO;
}
} else {
if (isNear(angle, THREE_PI_OVER_TWO)) {
return THREE_PI_OVER_TWO;
} else if (isNear(angle, TWO_PI)) {
return 0;
}
}
return angle;
}
/**
* Tests if the two {@code double} values are near to each other.
* It is recommended to use this method instead of testing if the two
* doubles are equal using an this expression: {@code value1 == value2}.
* The reason being, that this expression might never become
* {@code true} due to the precision of double values.
* Whether or not the specified doubles are near to each other is defined by
* the following expression:
* {@code (Math.abs(value1 - value2) < .00001)}
*
* @param value1 the first double value
* @param value2 the second double value
* @return {@code true} if the two doubles are near to each other;
* {@code false} otherwise.
*/
public static boolean isNear(double value1, double value2) {
return (Math.abs(value1 - value2) < NEAR_DELTA);
}
}
Returns n!. Shorthand for n Factorial, the product of the numbers 1,...,n.
import java.io.File;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
public class Main {
/**
* Returns n!. Shorthand for <code>n</code> , the
* product of the numbers <code>1,...,n</code> as a <code>double</code>.
*
* <Strong>Preconditions</strong>:
* <ul>
* <li> <code>n >= 0</code> (otherwise
* <code>IllegalArgumentException</code> is thrown)</li>
* <li> The result is small enough to fit into a <code>double</code>. The
* largest value of <code>n</code> for which <code>n!</code> <
* Double.MAX_VALUE</code> is 170. If the computed value exceeds
* Double.MAX_VALUE, Double.POSITIVE_INFINITY is returned</li>
* </ul>
*
*
* @param n argument
* @return <code>n!</code>
* @throws IllegalArgumentException if n < 0
*/
public static double factorialDouble(final int n) {
if (n < 0) {
throw new IllegalArgumentException("must have n >= 0 for n!");
}
return Math.floor(Math.exp(factorialLog(n)) + 0.5);
}
/**
* Returns the natural logarithm of n!.
*
* <Strong>Preconditions</strong>:
* <ul>
* <li> <code>n >= 0</code> (otherwise
* <code>IllegalArgumentException</code> is thrown)</li>
* </ul>
*
* @param n argument
* @return <code>n!</code>
* @throws IllegalArgumentException if preconditions are not met.
*/
public static double factorialLog(final int n) {
if (n < 0) {
throw new IllegalArgumentException("must have n > 0 for n!");
}
double logSum = 0;
for (int i = 2; i <= n; i++) {
logSum += Math.log((double)i);
}
return logSum;
}
}
Returns n!. Shorthand for n Factorial, the product of the numbers 1,...,n as a double.
import java.io.File;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
public class Main {
/**
* Returns n!. Shorthand for <code>n</code> , the
* product of the numbers <code>1,...,n</code> as a <code>double</code>.
*
* <Strong>Preconditions</strong>:
* <ul>
* <li> <code>n >= 0</code> (otherwise
* <code>IllegalArgumentException</code> is thrown)</li>
* <li> The result is small enough to fit into a <code>double</code>. The
* largest value of <code>n</code> for which <code>n!</code> <
* Double.MAX_VALUE</code> is 170. If the computed value exceeds
* Double.MAX_VALUE, Double.POSITIVE_INFINITY is returned</li>
* </ul>
*
*
* @param n argument
* @return <code>n!</code>
* @throws IllegalArgumentException if n < 0
*/
public static double factorialDouble(final int n) {
if (n < 0) {
throw new IllegalArgumentException("must have n >= 0 for n!");
}
return Math.floor(Math.exp(factorialLog(n)) + 0.5);
}
/**
* Returns the natural logarithm of n!.
*
* <Strong>Preconditions</strong>:
* <ul>
* <li> <code>n >= 0</code> (otherwise
* <code>IllegalArgumentException</code> is thrown)</li>
* </ul>
*
* @param n argument
* @return <code>n!</code>
* @throws IllegalArgumentException if preconditions are not met.
*/
public static double factorialLog(final int n) {
if (n < 0) {
throw new IllegalArgumentException("must have n > 0 for n!");
}
double logSum = 0;
for (int i = 2; i <= n; i++) {
logSum += Math.log((double)i);
}
return logSum;
}
}
Returns the hyperbolic cosine of x.
import java.io.File;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
public class Main {
/**
* Returns the of x.
*
* @param x double value for which to find the hyperbolic cosine
* @return hyperbolic cosine of x
*/
public static double cosh(double x) {
return (Math.exp(x) + Math.exp(-x)) / 2.0;
}
}
Returns the hyperbolic sine of x.
import java.math.BigDecimal;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
public class Main {
/**
* Returns the of x.
*
* @param x double value for which to find the hyperbolic sine
* @return hyperbolic sine of x
*/
public static double sinh(double x) {
return (Math.exp(x) - Math.exp(-x)) / 2.0;
}
}
Returns the natural logarithm of n!.
import java.io.File;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
public class Main {
/**
* Returns the natural logarithm of n!.
*
* <Strong>Preconditions</strong>:
* <ul>
* <li> <code>n >= 0</code> (otherwise
* <code>IllegalArgumentException</code> is thrown)</li>
* </ul>
*
* @param n argument
* @return <code>n!</code>
* @throws IllegalArgumentException if preconditions are not met.
*/
public static double factorialLog(final int n) {
if (n < 0) {
throw new IllegalArgumentException("must have n > 0 for n!");
}
double logSum = 0;
for (int i = 2; i <= n; i++) {
logSum += Math.log((double)i);
}
return logSum;
}
}
Returns the natural log of the (http://mathworld.wolfram.com/BinomialCoefficient.html) Binomial Coefficient
import java.io.File;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
public class Main {
/**
* Returns the natural <code>log</code> of the , "<code>n choose k</code>", the number of
* <code>k</code>-element subsets that can be selected from an
* <code>n</code>-element set.
*
* <Strong>Preconditions</strong>:
* <ul>
* <li> <code>0 <= k <= n </code> (otherwise
* <code>IllegalArgumentException</code> is thrown)</li>
* </ul>
*
* @param n the size of the set
* @param k the size of the subsets to be counted
* @return <code>n choose k</code>
* @throws IllegalArgumentException if preconditions are not met.
*/
public static double binomialCoefficientLog(final int n, final int k) {
if (n < k) {
throw new IllegalArgumentException(
"must have n >= k for binomial coefficient (n,k)");
}
if (n < 0) {
throw new IllegalArgumentException(
"must have n >= 0 for binomial coefficient (n,k)");
}
if ((n == k) || (k == 0)) {
return 0;
}
if ((k == 1) || (k == n - 1)) {
return Math.log((double)n);
}
double logSum = 0;
// n!/k!
for (int i = k + 1; i <= n; i++) {
logSum += Math.log((double)i);
}
// divide by (n-k)!
for (int i = 2; i <= n - k; i++) {
logSum -= Math.log((double)i);
}
return logSum;
}
}
Round Java float and double numbers using Math.round
public class Main {
public static void main(String[] args) {
System.out.println(Math.round(10f));
System.out.println(Math.round(2.5f));
System.out.println(Math.round(-1.4f));
System.out.println(Math.round(-2.5f));
}
}
/*
10
3
-1
-2
*/
Round the given value to the specified number of decimal places. The value is rounded using the BigDecimal.ROUND_HALF_UP method.
import java.math.BigDecimal;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
public class Main {
/**
* Round the given value to the specified number of decimal places. The
* value is rounded using the {@link BigDecimal#ROUND_HALF_UP} method.
*
* @param x the value to round.
* @param scale the number of digits to the right of the decimal point.
* @return the rounded value.
* @since 1.1
*/
public static double round(double x, int scale) {
return round(x, scale, BigDecimal.ROUND_HALF_UP);
}
/**
* Round the given value to the specified number of decimal places. The
* value is rounded using the given method which is any method defined in
* {@link BigDecimal}.
*
* @param x the value to round.
* @param scale the number of digits to the right of the decimal point.
* @param roundingMethod the rounding method as defined in
* {@link BigDecimal}.
* @return the rounded value.
* @since 1.1
*/
public static double round(double x, int scale, int roundingMethod) {
try {
return (new BigDecimal
(Double.toString(x))
.setScale(scale, roundingMethod))
.doubleValue();
} catch (NumberFormatException ex) {
if (Double.isInfinite(x)) {
return x;
} else {
return Double.NaN;
}
}
}
}
sqrt(a^2 + b^2) without under/overflow
public class Maths {
/** sqrt(a^2 + b^2) without under/overflow. **/
public static double hypot(double a, double b) {
double r;
if (Math.abs(a) > Math.abs(b)) {
r = b/a;
r = Math.abs(a)*Math.sqrt(1+r*r);
} else if (b != 0) {
r = a/b;
r = Math.abs(b)*Math.sqrt(1+r*r);
} else {
r = 0.0;
}
return r;
}
}
Testing the Math class methods
public class MainClass
{
public static void main( String args[] )
{
System.out.printf( "Math.abs( 23.7 ) = %f\n", Math.abs( 23.7 ) );
System.out.printf( "Math.abs( 0.0 ) = %f\n", Math.abs( 0.0 ) );
System.out.printf( "Math.abs( -23.7 ) = %f\n", Math.abs( -23.7 ) );
System.out.printf( "Math.ceil( 9.2 ) = %f\n", Math.ceil( 9.2 ) );
System.out.printf( "Math.ceil( -9.8 ) = %f\n", Math.ceil( -9.8 ) );
System.out.printf( "Math.cos( 0.0 ) = %f\n", Math.cos( 0.0 ) );
System.out.printf( "Math.exp( 1.0 ) = %f\n", Math.exp( 1.0 ) );
System.out.printf( "Math.exp( 2.0 ) = %f\n", Math.exp( 2.0 ) );
System.out.printf( "Math.floor( 9.2 ) = %f\n", Math.floor( 9.2 ) );
System.out.printf( "Math.floor( -9.8 ) = %f\n", Math.floor( -9.8 ) );
System.out.printf( "Math.log( Math.E ) = %f\n", Math.log( Math.E ) );
System.out.printf( "Math.log( Math.E * Math.E ) = %f\n", Math.log( Math.E * Math.E ) );
System.out.printf( "Math.max( 2.3, 12.7 ) = %f\n",Math.max( 2.3, 12.7 ) );
System.out.printf( "Math.max( -2.3, -12.7 ) = %f\n",Math.max( -2.3, -12.7 ) );
System.out.printf( "Math.min( 2.3, 12.7 ) = %f\n",Math.min( 2.3, 12.7 ) );
System.out.printf( "Math.min( -2.3, -12.7 ) = %f\n",Math.min( -2.3, -12.7 ) );
System.out.printf( "Math.pow( 2.0, 7.0 ) = %f\n",Math.pow( 2.0, 7.0 ) );
System.out.printf( "Math.pow( 9.0, 0.5 ) = %f\n", Math.pow( 9.0, 0.5 ) );
System.out.printf( "Math.sin( 0.0 ) = %f\n", Math.sin( 0.0 ) );
System.out.printf( "Math.sqrt( 900.0 ) = %f\n", Math.sqrt( 900.0 ) );
System.out.printf( "Math.sqrt( 9.0 ) = %f\n", Math.sqrt( 9.0 ) );
System.out.printf( "Math.tan( 0.0 ) = %f\n", Math.tan( 0.0 ) );
}
}
Math.abs( 23.7 ) = 23.700000 Math.abs( 0.0 ) = 0.000000 Math.abs( -23.7 ) = 23.700000 Math.ceil( 9.2 ) = 10.000000 Math.ceil( -9.8 ) = -9.000000 Math.cos( 0.0 ) = 1.000000 Math.exp( 1.0 ) = 2.718282 Math.exp( 2.0 ) = 7.389056 Math.floor( 9.2 ) = 9.000000 Math.floor( -9.8 ) = -10.000000 Math.log( Math.E ) = 1.000000 Math.log( Math.E * Math.E ) = 2.000000 Math.max( 2.3, 12.7 ) = 12.700000 Math.max( -2.3, -12.7 ) = -2.300000 Math.min( 2.3, 12.7 ) = 2.300000 Math.min( -2.3, -12.7 ) = -12.700000 Math.pow( 2.0, 7.0 ) = 128.000000 Math.pow( 9.0, 0.5 ) = 3.000000 Math.sin( 0.0 ) = 0.000000 Math.sqrt( 900.0 ) = 30.000000 Math.sqrt( 9.0 ) = 3.000000 Math.tan( 0.0 ) = 0.000000
Use math functions
public class MainClass {
public static void main(String args[]) {
double loanAmount = 0;
double top = 2 * 5 / 1200;
double bot = 1 - Math.exp(5 * (-12) * Math.log(1 + 7 / 1200));
System.out.println(loanAmount);
System.out.println(top);
System.out.println(bot);
}
}
Value is rounded using the given method which is any method defined in BigDecimal
import java.math.BigDecimal;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
public class Main {
/**
* Round the given value to the specified number of decimal places. The
* value is rounded using the given method which is any method defined in
* {@link BigDecimal}.
*
* @param x the value to round.
* @param scale the number of digits to the right of the decimal point.
* @param roundingMethod the rounding method as defined in
* {@link BigDecimal}.
* @return the rounded value.
* @since 1.1
*/
public static double round(double x, int scale, int roundingMethod) {
try {
return (new BigDecimal
(Double.toString(x))
.setScale(scale, roundingMethod))
.doubleValue();
} catch (NumberFormatException ex) {
if (Double.isInfinite(x)) {
return x;
} else {
return Double.NaN;
}
}
}
}