Java/Development Class/Math

Материал из Java эксперт
Версия от 06:59, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Содержание

Absolute value

     
public class SquareRoot {
  public static void main(String[] args) {
    System.out.println(Math.abs(1 - 100));
  }
}





Applying the quadratic formula

     
/*
Java Programming for Engineers
Julio Sanchez
Maria P. Canton

ISBN: 0849308100
Publisher: CRC Press
*/
// Java for Engineers
//Filename: QuadSolv
//Reference: Chapter 24
//Description:
//         Applying the quadratic formula
//Requires:
//         Keyin class in current directory

strictfp class QuadSolv
{
public static void main(String[] args)
{
      
     double a, b, c, discr, root1, root2;
     // Apllying the quadratic formula
     // Obtain sides from user
     System.out.println("Applying the quadratic formula");
     a = 1d;
     b = 2d;
     c = 3d;
     // Solve the discriminant (SQRT (b^2 - 4ac)
     discr = Math.sqrt((b * b) - (4 * a * c));
     System.out.println("Discriminant = " + discr);
     // Determine number of roots
     // if discr > 0 equation has 2 real roots
     // if discr == 0 equation has a repeated real root
     // if discr < 0 equation has imaginary roots
     // if discr is NaN equation has no roots
     // Test for NaN
     if(Double.isNaN(discr))
        System.out.println("Equation has no roots");
     
     if(discr > 0)
     {
        System.out.println("Equation has 2 roots");
        root1 = (-b + discr)/2 * a;
        root2 = (-b - discr)/2 * a;
        System.out.println("First root = " + root1);
        System.out.println("Second roor = " + root2);
      }
      if(discr == 0)
      {
        System.out.println("Equation has 1 root");
        root1 = (-b + discr)/2 * a;
        System.out.println("Root = " + root1);
      }
       if(discr < 0)
         System.out.println("Equation has imaginary roots");
}
}





Basic Math Demo

     
/*
 * Copyright (c) 2006 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:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution 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, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
public class BasicMathDemo {
    public static void main(String[] args) {
        double aNumber = -191.635;
        System.out.println("The absolute value of " + aNumber + " is " + Math.abs(aNumber));
        System.out.println("The ceiling of " + aNumber + " is " + Math.ceil(aNumber));
        System.out.println("The floor of " + aNumber + " is " + Math.floor(aNumber));
        System.out.println("The rint of " + aNumber + " is " + Math.rint(aNumber));
    }
}





Caclulate the factorial of N

    
/* 
 * JGraphT : a free Java graph-theory library
 * 
 *
 * Project Info:  http://jgrapht.sourceforge.net/
 * Project Creator:  Barak Naveh (http://sourceforge.net/users/barak_naveh)
 *
 * (C) Copyright 2003-2007, by Barak Naveh and Contributors.
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, write to the Free Software Foundation,
 * Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 */
/* -----------------
 * MathUtil.java
 * -----------------
 * (C) Copyright 2005-2007, by Assaf Lehr and Contributors.
 *
 * Original Author:  Assaf Lehr
 * Contributor(s):   -
 *
 * $Id: MathUtil.java 568 2007-09-30 00:12:18Z perfecthash $
 *
 * Changes
 * -------
 */
/**
 * Math Utilities. Currently contains the following:
 * <li>factorial(int N) - caclulate the factorial of N (aka N!)
 *
 * @author Assaf
 * @since May 30, 2005
 */
public class MathUtil
{
    //~ Methods ----------------------------------------------------------------
    public static long factorial(int N)
    {
        long multi = 1;
        for (int i = 1; i <= N; i++) {
            multi = multi * i;
        }
        return multi;
    }
}
// End MathUtil.java





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&euml;l Grosbois and
 * Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel
 * Askel&ouml;f (Ericsson Radio Systems AB); and Bertrand Berthelot, David
 * Bouchard, F&eacute;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;
    }
   
}





Calculating hyperbolic functions

     
strictfp class HypFun {
  public static void main(String[] args) {
    double rads, degs, sinHA, cosHA, tanHA, asinHA;
    // Obtain angle in degrees from user
    degs = 20d;
    // Convert degrees to radian
    rads = Math.toRadians(degs);
    // Calculate hyperbolic sine
    sinHA = (Math.exp(rads) - Math.exp(-rads)) / 2;
    System.out.println("Hyperbolic sine = " + sinHA);
    // Calculate Hyperbolic cosine
    cosHA = (Math.exp(rads) + Math.exp(-rads)) / 2;
    System.out.println("Hyperbolic cosine = " + cosHA);
    // Calculate hyperbolic tangent
    tanHA = sinHA / cosHA;
    System.out.println("Hyperbolic tangent = " + tanHA);
    // Calculate hyperbolic arc-sine
    asinHA = Math.log(sinHA + Math.sqrt((sinHA * sinHA) + 1.0));
    degs = Math.toDegrees(asinHA);
    System.out.println("Arc hyperbolic sine = " + degs);
  }
}





Calculating trigonometric functions

     
strictfp class TrigFun {
  public static void main(String[] args) {
    double rads, degs, tanA, coTanA;
    // Obtain angle in degrees from user
    degs = 120d;
    // Convert degrees to radian
    rads = Math.toRadians(degs);
    // Calculate tangent
    tanA = Math.tan(rads);
    System.out.println("Tangent = " + tanA);
    // Calculate cotangent
    coTanA = 1.0 / Math.tan(rads);
    System.out.println("Cotangent = " + coTanA);
    // Calculate arc-tangent
    rads = Math.atan(tanA);
    degs = Math.toDegrees(rads);
    System.out.println("Arc tangent: " + degs);
    // Calculate arc-cotangent
    rads = Math.atan(1 / coTanA);
    degs = Math.toDegrees(rads);
    System.out.println("Arc cotangent: " + degs);
  }
}





Complex Number Demo

     
/*
3.0+5.0i
3.0+5.0i.getReal() = 3.0
3.0+5.0i + 2.0-2.0i = 5.0+3.0i
3.0+5.0i + 2.0-2.0i = 5.0+3.0i
3.0+5.0i * 2.0-2.0i = 16.0+4.0i
-0.5+2.0i
*/


/** A class to test Complex Numbers. 
 * @author Ian F. Darwin, http://www.darwinsys.ru/
 * @version $Id: ComplexDemo.java,v 1.6 2004/05/13 22:28:59 ian Exp $
 */
public class ComplexDemo {
  /** The program */
  public static void main(String[] args) {
    Complex c = new Complex(3,  5);
    Complex d = new Complex(2, -2);
    System.out.println(c);
    System.out.println(c + ".getReal() = " + c.getReal());
    System.out.println(c + " + " + d + " = " + c.add(d));
    System.out.println(c + " + " + d + " = " + Complex.add(c, d));
    System.out.println(c + " * " + d + " = " + c.multiply(d));
    System.out.println(Complex.divide(c, d));
  }
}

/** A class to represent Complex Numbers. A Complex object is
 * immutable once created; the add, subtract and multiply routines
 * return newly-created Complex objects containing the results.
 *
 * @author Ian F. Darwin, inspired by David Flanagan.
 * @version $Id: Complex.java,v 1.3 2004/05/13 22:28:59 ian Exp $
 */
class Complex {
  /** The real part */
  private double r;
  /** The imaginary part */
  private double i;
  /** Construct a Complex */
  Complex(double rr, double ii) {
    r = rr;
    i = ii;
  }
  /** Display the current Complex as a String, for use in
   * println() and elsewhere.
   */
  public String toString() {
    StringBuffer sb = new StringBuffer().append(r);
    if (i>0)
      sb.append("+"); // else append(i) appends - sign
    return sb.append(i).append("i").toString();
  }
  /** Return just the Real part */
  public double getReal() {
    return r;
  }
  /** Return just the Real part */
  public double getImaginary() {
    return i;
  }
  /** Return the magnitude of a complex number */
  public double magnitude() {
    return Math.sqrt(r*r + i*i);
  }
  /** Add another Complex to this one
   */
  public Complex add(Complex other) {
    return add(this, other);
  }
  /** Add two Complexes
   */
  public static Complex add(Complex c1, Complex c2) {
    return new Complex(c1.r+c2.r, c1.i+c2.i);
  }
  /** Subtract another Complex from this one
   */
  public Complex subtract(Complex other) {
    return subtract(this, other);
  }
  /** Subtract two Complexes
   */
  public static Complex subtract(Complex c1, Complex c2) {
    return new Complex(c1.r-c2.r, c1.i-c2.i);
  }
  /** Multiply this Complex times another one
   */
  public Complex multiply(Complex other) {
    return multiply(this, other);
  }
  /** Multiply two Complexes
   */
  public static Complex multiply(Complex c1, Complex c2) {
    return new Complex(c1.r*c2.r - c1.i*c2.i, c1.r*c2.i + c1.i*c2.r);
  }
  /** Divide c1 by c2.
   * @author Gisbert Selke.
   */
  public static Complex divide(Complex c1, Complex c2) {
    return new Complex(
      (c1.r*c2.r+c1.i*c2.i)/(c2.r*c2.r+c2.i*c2.i),
      (c1.i*c2.r-c1.r*c2.i)/(c2.r*c2.r+c2.i*c2.i));
  }
  
  /* Compare this Complex number with another
   */
  public boolean equals(Object o) {
    if (!(o instanceof Complex))
      throw new IllegalArgumentException(
          "Complex.equals argument must be a Complex");
    Complex other = (Complex)o;
    return r == other.r && i == other.i;
  }
  
  /* Generate a hashCode; not sure how well distributed these are.
   */
  public int hashCode() {
    return (int)( r) |  (int)i;
  }
}





Contains static definition for matrix math methods.

   
/*
 * Soya3D
 * Copyright (C) 1999-2000 Jean-Baptiste LAMY (Artiste on the web)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Library General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

/**
 * Contains static definition for matrix math methods.
 * 
 * Here, a matrix is a float[16], and a vector or a point a float[3] (contrary to other part of Opale.Soya, where a point is 3 coords + a CoordSyst).
 * 
 * @author Artiste on the Web
 */
public class Matrix extends Object {
  private Matrix() {  }
  /**
   * The value of PI in float.
   */
  public static final float PI = (float) java.lang.Math.PI;
  
  public static final float EPSILON = 0.001f;
  public static float pow2(float f) { return f*f; }
  
  private static float[][] stock = new float[1000][];
  
  /**
   * Inverts a 4*4 matrix. Warning : this method works only if m[3] = m[7] = m[11] = 0f
   * and m[15] = 1f.
   * @param m the matrix
   * @return the inverted matrix or null if m is not invertable
   */
  public static final float[] matrixInvert(float[] m) { // Optimized!
    float[] r = matrixInvert3_3(m);
    if(r == null) return null;
    r[12] = -(m[12] * r[0] + m[13] * r[4] + m[14] * r[ 8]);
    r[13] = -(m[12] * r[1] + m[13] * r[5] + m[14] * r[ 9]);
    r[14] = -(m[12] * r[2] + m[13] * r[6] + m[14] * r[10]);
    return r;
  }
  
  /**
   * Inverts a 3*3 part of a 4*4 matrix.
   * It IS NOT a complete inversion because other values in the matrix (such as the translation part) are set to 0.
   * It isn"t a bug, other classes assume this.
   * @param m the matrix that will be inverted
   * @return the inverted matrix. Value 12, 13, 14 that represent the translation are set to 0. Return null if the matrix is not invertable
   */
  public static final float[] matrixInvert3_3(float[] m) {
    float[] r = new float[16];
    float det = m[0] * (m[5] * m[10] - m[9] * m[6])
              - m[4] * (m[1] * m[10] - m[9] * m[2])
              + m[8] * (m[1] * m[ 6] - m[5] * m[2]);
    if(det == 0f) return null;
    det = 1f / det;
    r[ 0] =   det * (m[5] * m[10] - m[9] * m[6]);
    r[ 4] = - det * (m[4] * m[10] - m[8] * m[6]);
    r[ 8] =   det * (m[4] * m[ 9] - m[8] * m[5]);
    r[ 1] = - det * (m[1] * m[10] - m[9] * m[2]);
    r[ 5] =   det * (m[0] * m[10] - m[8] * m[2]);
    r[ 9] = - det * (m[0] * m[ 9] - m[8] * m[1]);
    r[ 2] =   det * (m[1] * m[ 6] - m[5] * m[2]);
    r[ 6] = - det * (m[0] * m[ 6] - m[4] * m[2]);
    r[10] =   det * (m[0] * m[ 5] - m[4] * m[1]);
    
    r[15] =   1f;
    return r;
  }

  /**
   * Multiply a 4*4 matrix by another, as if they were 3*3.
   * @param a the first / left matrix
   * @param b the second / right matrix
   * @return the result
   */
  public static final float[] matrixMultiply(float[] b, float[] a) {
    float[] r = new float[16];
    
    r[ 0] = a[ 0] * b[ 0] + a[ 1] * b[ 4] + a[ 2] * b[ 8];
    r[ 4] = a[ 4] * b[ 0] + a[ 5] * b[ 4] + a[ 6] * b[ 8];
    r[ 8] = a[ 8] * b[ 0] + a[ 9] * b[ 4] + a[10] * b[ 8];
    r[12] = a[12] * b[ 0] + a[13] * b[ 4] + a[14] * b[ 8] + b[12];
    
    r[ 1] = a[ 0] * b[ 1] + a[ 1] * b[ 5] + a[ 2] * b[ 9];
    r[ 5] = a[ 4] * b[ 1] + a[ 5] * b[ 5] + a[ 6] * b[ 9];
    r[ 9] = a[ 8] * b[ 1] + a[ 9] * b[ 5] + a[10] * b[ 9];
    r[13] = a[12] * b[ 1] + a[13] * b[ 5] + a[14] * b[ 9] + b[13];
    
    r[ 2] = a[ 0] * b[ 2] + a[ 1] * b[ 6] + a[ 2] * b[10];
    r[ 6] = a[ 4] * b[ 2] + a[ 5] * b[ 6] + a[ 6] * b[10];
    r[10] = a[ 8] * b[ 2] + a[ 9] * b[ 6] + a[10] * b[10];
    r[14] = a[12] * b[ 2] + a[13] * b[ 6] + a[14] * b[10] + b[14];
    
    r[ 3] = 0;
    r[ 7] = 0;
    r[11] = 0;
    r[15] = 1;
    return r;
  }
  /**
   * Multiply a 4*4 matrix by another.
   * @param a the first / left matrix
   * @param b the second / right matrix
   * @return the result
   */
  public static final float[] matrixMultiply_4(float[] b, float[] a) {
    float[] r = new float[16];
    
    r[ 0] = a[ 0] * b[ 0] + a[ 1] * b[ 4] + a[ 2] * b[ 8] + a[ 3] * b[12];
    r[ 4] = a[ 4] * b[ 0] + a[ 5] * b[ 4] + a[ 6] * b[ 8] + a[ 7] * b[12];
    r[ 8] = a[ 8] * b[ 0] + a[ 9] * b[ 4] + a[10] * b[ 8] + a[11] * b[12];
    r[12] = a[12] * b[ 0] + a[13] * b[ 4] + a[14] * b[ 8] + a[15] * b[12];
    
    r[ 1] = a[ 0] * b[ 1] + a[ 1] * b[ 5] + a[ 2] * b[ 9] + a[ 3] * b[13];
    r[ 5] = a[ 4] * b[ 1] + a[ 5] * b[ 5] + a[ 6] * b[ 9] + a[ 7] * b[13];
    r[ 9] = a[ 8] * b[ 1] + a[ 9] * b[ 5] + a[10] * b[ 9] + a[11] * b[13];
    r[13] = a[12] * b[ 1] + a[13] * b[ 5] + a[14] * b[ 9] + a[15] * b[13];
    
    r[ 2] = a[ 0] * b[ 2] + a[ 1] * b[ 6] + a[ 2] * b[10] + a[ 3] * b[14];
    r[ 6] = a[ 4] * b[ 2] + a[ 5] * b[ 6] + a[ 6] * b[10] + a[ 7] * b[14];
    r[10] = a[ 8] * b[ 2] + a[ 9] * b[ 6] + a[10] * b[10] + a[11] * b[14];
    r[14] = a[12] * b[ 2] + a[13] * b[ 6] + a[14] * b[10] + a[15] * b[14];
    
    r[ 3] = a[ 0] * b[ 3] + a[ 1] * b[ 7] + a[ 2] * b[11] + a[ 3] * b[15];
    r[ 7] = a[ 4] * b[ 3] + a[ 5] * b[ 7] + a[ 6] * b[11] + a[ 7] * b[15];
    r[11] = a[ 8] * b[ 3] + a[ 9] * b[ 7] + a[10] * b[11] + a[11] * b[15];
    r[15] = a[12] * b[ 3] + a[13] * b[ 7] + a[14] * b[11] + a[15] * b[15];
    return r;
  }
  
  /**
   * Multiply a point by a 4*4 matrix.
   * @param m the matrix
   * @param p the point
   * the resulting point
   */
  public static final float[] pointMultiplyByMatrix(float[] m, float[] p) { // Assume v[3] = 1.
    float[] r = { p[0] * m[0] + p[1] * m[4] + p[2] * m[ 8] + m[12],
                  p[0] * m[1] + p[1] * m[5] + p[2] * m[ 9] + m[13],
                  p[0] * m[2] + p[1] * m[6] + p[2] * m[10] + m[14]
    };
    return r;
  }
  /**
   * Multiply a vector by a 4*4 matrix.
   * @param m the matrix
   * @param v the vector
   * @return the resulting vector
   */
  public static final float[] vectorMultiplyByMatrix(float[] m, float[] v) {
    float[] r = { v[0] * m[0] + v[1] * m[4] + v[2] * m[ 8],
                  v[0] * m[1] + v[1] * m[5] + v[2] * m[ 9],
                  v[0] * m[2] + v[1] * m[6] + v[2] * m[10]
    };
    return r;
  }
  /**
   * Compare 2 matrix.
   * @param a the first matrix
   * @param b the second matrix
   * @return true if a and b are equal (or very near)
   */
  public static final boolean matrixEqual(float[] a, float[] b) {
    for(int i = 0; i < 16; i++) {
      if(Math.abs(a[i] - b[i]) > EPSILON) return false;
    }
    return true;
  }
  /**
   * Convert a matrix into a string. Useful for debuging soya.
   * @param m the matrix
   * @return the string
   */
  public static final String matrixToString(float[] m) {
    String s = "matrix 4_4 {\n";
    s = s + Float.toString(m[ 0]) + " " + Float.toString(m[ 4]) + " " + Float.toString(m[ 8]) + "\n";
    s = s + Float.toString(m[ 1]) + " " + Float.toString(m[ 5]) + " " + Float.toString(m[ 9]) + "\n";
    s = s + Float.toString(m[ 2]) + " " + Float.toString(m[ 6]) + " " + Float.toString(m[10]) + "\n";
    s = s + Float.toString(m[ 3]) + " " + Float.toString(m[ 7]) + " " + Float.toString(m[11]) + "\n";
    s = s + "X: " + Float.toString(m[12]) + " Y: " + Float.toString(m[13]) + " Z: " + Float.toString(m[14]) + " W: " + Float.toString(m[15]) + "\n";
    s = s + "}";
    return s;
  }
  /**
   * Create a new identity matrix.
   * @return an identity matrix
   */
  public static final float[] matrixIdentity() {
    float[] m = new float[16];
    matrixIdentity(m);
    return m;
  }
  /**
   * Set a matrix to identity matrix.
   * @param m the matrix
   */
  public static final void matrixIdentity(float[] m) {
    m[ 0] = 1f;
    m[ 1] = 0f;
    m[ 2] = 0f;
    m[ 3] = 0f;
    m[ 4] = 0f;
    m[ 5] = 1f;
    m[ 6] = 0f;
    m[ 7] = 0f;
    m[ 8] = 0f;
    m[ 9] = 0f;
    m[10] = 1f;
    m[11] = 0f;
    m[12] = 0f;
    m[13] = 0f;
    m[14] = 0f;
    m[15] = 1f;
  }
  /**
   * Create a scale matrix.
   * @param x the x factor of the scaling
   * @param y the y factor of the scaling 
   * @param z the z factor of the scaling
   * @return the matrix
   */
  public static float[] matrixScale(float x, float y, float z) {
    float[] m2 = { x,  0f, 0f, 0f,
                   0f, y,  0f, 0f,
                   0f, 0f, z,  0f,
                   0f, 0f, 0f, 1f };
    return m2;
  }
  /**
   * Scale a matrix (this is equivalent to OpenGL glScale* ).
   * @param m the matrix
   * @param x the x factor of the scaling
   * @param y the y factor of the scaling
   * @param z the z factor of the scaling
   * @return the scaled matrix
   */
  public static float[] matrixScale(float[] m, float x, float y, float z) {
    float r[] = new float[16];
    r[ 0] = x * m[ 0];
    r[ 4] = y * m[ 4];
    r[ 8] = z * m[ 8];
    r[12] = m[12];
    r[ 1] = x * m[ 1];
    r[ 5] = y * m[ 5];
    r[ 9] = z * m[ 9];
    r[13] = m[13];
    r[ 2] = x * m[ 2];
    r[ 6] = y * m[ 6];
    r[10] = z * m[10];
    r[14] = m[14];
    r[ 3] = 0;
    r[ 7] = 0;
    r[11] = 0;
    r[15] = 1;
    return r;
//    return matrixMultiply(m, matrixScale(x, y, z));
  }
  
  /**
   * Create a lateral rotation matrix (lateral rotation is around a (0, 1, 0) axis).
   * @param angle the angle of the rotation
   * @return the matrix
   */
  public static float[] matrixRotateLateral(float angle) {
    if(angle == 0f) return matrixIdentity();
    angle = (float) Math.toRadians(angle);
    float cos = (float) java.lang.Math.cos(angle);
    float sin = (float) java.lang.Math.sin(angle);
    float[] m2 = { cos, 0f, -sin, 0f,
                   0f , 1f,  0f , 0f,
                   sin, 0f,  cos, 0f,
                   0f , 0f,  0f , 1f };
    return m2;
  }
  /**
   * Laterally rotate a matrix (lateral rotation is around a (0, 1, 0) axis).
   * @param angle the angle of the rotation
   * @param m the matrix to rotate
   * @return the resulting matrix
   */
  public static float[] matrixRotateLateral(float[] m, float angle) {
    if(angle == 0f) return matrixIdentity();
    angle = (float) Math.toRadians(angle);
    float cos = (float) java.lang.Math.cos(angle);
    float sin = (float) java.lang.Math.sin(angle);
    float r[] = new float[16];
    r[ 0] = m[ 0] * cos + m[ 2] * sin;
    r[ 4] = m[ 4] * cos + m[ 6] * sin;
    r[ 8] = m[ 8] * cos + m[10] * sin;
    r[12] = m[12] * cos + m[14] * sin;
    r[ 1] = m[ 1];
    r[ 5] = m[ 5];
    r[ 9] = m[ 9];
    r[13] = m[13];
    r[ 2] = -m[ 0] * sin + m[ 2] * cos;
    r[ 6] = -m[ 4] * sin + m[ 6] * cos;
    r[10] = -m[ 8] * sin + m[10] * cos;
    r[14] = -m[12] * sin + m[14] * cos;
    r[ 3] = 0;
    r[ 7] = 0;
    r[11] = 0;
    r[15] = 1;
    return r;
//    return matrixMultiply(matrixRotateLateral(angle), m);
  }
  /**
   * Create a vertical rotation matrix (vertical rotation is around a (1, 0, 0) axis).
   * @param angle the angle of the rotation
   * @return the matrix
   */
  public static float[] matrixRotateVertical(float angle) {
    if(angle == 0f) return matrixIdentity();
    angle = (float) Math.toRadians(angle);
    float cos = (float) java.lang.Math.cos(angle);
    float sin = (float) java.lang.Math.sin(angle);
    float[] m2 = { 1f,  0f , 0f , 0f,
                   0f,  cos, sin, 0f,
                   0f, -sin, cos, 0f,
                   0f,  0f , 0f , 1f };
    return m2;
  }
  /**
   * Vertically rotate a matrix (vertical rotation is around a (1, 0, 0) axis).
   * @param angle the angle of the rotation
   * @param m the matrix to rotate
   * @return the resulting matrix
   */
  public static float[] matrixRotateVertical(float[] m, float angle) {
    if(angle == 0f) return matrixIdentity();
    angle = (float) Math.toRadians(angle);
    float cos = (float) java.lang.Math.cos(angle);
    float sin = (float) java.lang.Math.sin(angle);
    float r[] = new float[16];
    r[ 0] = m[ 0];
    r[ 4] = m[ 4];
    r[ 8] = m[ 8];
    r[12] = m[12];
    r[ 1] = m[ 1] * cos - m[ 2] * sin;
    r[ 5] = m[ 5] * cos - m[ 6] * sin;
    r[ 9] = m[ 9] * cos - m[10] * sin;
    r[13] = m[13] * cos - m[14] * sin;
    r[ 2] = m[ 1] * sin + m[ 2] * cos;
    r[ 6] = m[ 5] * sin + m[ 6] * cos;
    r[10] = m[ 9] * sin + m[10] * cos;
    r[14] = m[13] * sin + m[14] * cos;
    r[ 3] = 0;
    r[ 7] = 0;
    r[11] = 0;
    r[15] = 1;
    return r;
//    return matrixMultiply(matrixRotateVertical(angle), m);
  }
  /**
   * Create a incline-rotation matrix (incline-rotation is around a (0, 0, 1) axis).
   * @param angle the angle of the rotation
   * @return the matrix
   */
  public static float[] matrixRotateIncline(float angle) {
    if(angle == 0f) return matrixIdentity();
    angle = (float) Math.toRadians(angle);
    float cos = (float) java.lang.Math.cos(angle);
    float sin = (float) java.lang.Math.sin(angle);
    float m2[] = { cos, sin, 0f, 0f,
                  -sin, cos, 0f, 0f,
                   0f , 0f , 1f, 0f,
                   0f , 0f , 0f, 1f };
    return m2;
  }
  /**
   * Incline a matrix (incline-rotation is around a (0, 0, 1) axis).
   * @param angle the angle of the rotation
   * @param m the matrix to rotate
   * @return the resulting matrix 
   */
  public static float[] matrixRotateIncline(float[] m, float angle) {
    if(angle == 0f) return matrixIdentity();
    angle = (float) Math.toRadians(angle);
    float cos = (float) java.lang.Math.cos(angle);
    float sin = (float) java.lang.Math.sin(angle);
    float r[] = new float[16];
    r[ 0] = m[ 0] * cos - m[ 1] * sin;
    r[ 4] = m[ 4] * cos - m[ 5] * sin;
    r[ 8] = m[ 8] * cos - m[ 9] * sin;
    r[12] = m[12] * cos - m[13] * sin;
    r[ 1] = m[ 0] * sin + m[ 1] * cos;
    r[ 5] = m[ 4] * sin + m[ 5] * cos;
    r[ 9] = m[ 8] * sin + m[ 9] * cos;
    r[13] = m[12] * sin + m[13] * cos;
    r[ 2] = m[ 2];
    r[ 6] = m[ 6];
    r[10] = m[10];
    r[14] = m[14];
    r[ 3] = 0;
    r[ 7] = 0;
    r[11] = 0;
    r[15] = 1;
    return r;
//    return matrixMultiply(matrixRotateIncline(angle), m);
  }
  /**
   * Create a rotation matrix.
   * @param angle the angle of the rotation
   * @param x the x coordinate of the rotation axis
   * @param y the y coordinate of the rotation axis
   * @param z the z coordinate of the rotation axis
   * @return the matrix
   */
  public static float[] matrixRotate(float angle, float x, float y, float z) {
    if(angle == 0f) return matrixIdentity();
    angle = (float) Math.toRadians(angle);
    float d = (float) java.lang.Math.sqrt(java.lang.Math.pow(x, 2) + java.lang.Math.pow(y, 2) + java.lang.Math.pow(z, 2));
    if(d != 1f) {
      x = x / d;
      y = y / d;
      z = z / d;
    }
    float cos = (float) java.lang.Math.cos(angle);
    float sin = (float) java.lang.Math.sin(angle);
    float co1 = 1f - cos;
    float m2[] = { x * x * co1 + cos    ,  y * x * co1 + z * sin, z * x * co1 - y * sin, 0f,
                   x * y * co1 - z * sin,  y * y * co1 + cos    , z * y * co1 + x * sin, 0f,
                   x * z * co1 + y * sin,  y * z * co1 - x * sin, z * z * co1 + cos    , 0f,
                   0f                   ,  0f                   , 0f                   , 1f };
    return m2;
  }
  /**
   * Rotate a matrix (this is equivalent to OpenGL glRotate*).
   * @param m the matrix to rotate
   * @param angle the angle of the rotation
   * @param x the x coordinate of the rotation axis
   * @param y the y coordinate of the rotation axis
   * @param z the z coordinate of the rotation axis
   * @return the resulting matrix
   */
  public static float[] matrixRotate(float[] m, float angle, float x, float y, float z) {
    return matrixMultiply(matrixRotate(angle, x, y, z), m);
  }
  /**
   *  Rotation  about an arbitrary Axis
   *  @param alpha the angle of the rotation
   *  @param p1 first axis point
   *  @param p2 second axis point
   *  @return the rotation matrix
   */
  public static float[] matrixRotate(float alpha, float[] p1, float[] p2){
    alpha = alpha * PI / 180f;
    
    float a1 = p1[0];
    float a2 = p1[1];
    float a3 = p1[2];
      
    //Compute the vector defines by point p1 and p2
    float v1 = p2[0] - a1 ;
    float v2 = p2[1] - a2 ;
    float v3 = p2[2] - a3 ;
        
    double theta = Math.atan2(v2, v1);
    double phi = Math.atan2(Math.sqrt(v1 * v1 + v2 * v2), v3);
    
    float cosAlpha, sinAlpha, sinPhi2; 
    float cosTheta, sinTheta, cosPhi2;
    float cosPhi, sinPhi, cosTheta2, sinTheta2 ; 
    
    cosPhi = (float) Math.cos(phi); cosTheta = (float) Math.cos(theta) ; cosTheta2 = (float) cosTheta * cosTheta ;
    sinPhi = (float) Math.sin(phi); sinTheta = (float) Math.sin(theta) ; sinTheta2 = (float) sinTheta * sinTheta ; 
  
    sinPhi2 = (float) sinPhi*sinPhi ;
    cosPhi2 = (float) cosPhi*cosPhi ;
    
    cosAlpha = (float) Math.cos(alpha) ;
    sinAlpha = (float) Math.sin(alpha) ;
    
    float c = (float) 1.0 - cosAlpha ; 
    
    float r11,r12,r13,r14,r21,r22,r23,r24,r31,r32,r33,r34;
    r11 =  cosTheta2 * ( cosAlpha * cosPhi2 +sinPhi2 ) + cosAlpha * sinTheta2 ;
    r12 = sinAlpha * cosPhi + c * sinPhi2 * cosTheta * sinTheta ; 
    r13 = sinPhi * (cosPhi * cosTheta * c - sinAlpha*sinTheta) ; 
    
    r21 = sinPhi2 * cosTheta * sinTheta*c - sinAlpha*cosPhi ; 
    r22 = sinTheta2 * (cosAlpha*cosPhi2 +sinPhi2) + cosAlpha*cosTheta2 ;
    r23 = sinPhi * (cosPhi*sinTheta*c + sinAlpha*cosTheta);
    
    r31 = sinPhi * (cosPhi*cosTheta*c + sinAlpha*sinTheta);
    r32 = sinPhi * (cosPhi*sinTheta*c - sinAlpha*cosTheta);
    r33 =  cosAlpha * sinPhi2 + cosPhi2 ;
    
    r14 = a1 - a1*r11 - a2*r21 - a3*r31 ;
    r24 = a2 - a1*r12 - a2*r22 - a3*r32 ;
    r34 = a3 - a1*r13 - a2*r23 - a3*r33 ;
    
    float[] m2 = { r11 , r12 , r13 , 0f,
                   r21 , r22 , r23 , 0f,
                   r31 , r32 , r33 , 0f,
                   r14 , r24 , r34 , 1f
    };  
    return m2;
  }
  /**
   *  Rotation  about an arbitrary Axis
   *  @param m the matrix to rotate
   *  @param alpha the angle of the rotation
   *  @param p1 first axis point
   *  @param p2 second axis point
   *  @return the rotated matrix
   */
  public static float[] matrixRotate(float[] m, float alpha, float[] p1, float[] p2) {
    return matrixMultiply(matrixRotate(alpha, p1, p2), m);
  }
  
  /**
   * Create a translation matrix.
   * @param x the x coordinate of the translation vector
   * @param y the y coordinate of the translation vector
   * @param z the z coordinate of the translation vector
   * @return the translation matrix
   */
  public static float[] matrixTranslate(float x, float y, float z) {
    float m2[] = { 1f, 0f, 0f, 0f,
                   0f, 1f, 0f, 0f,
                   0f, 0f, 1f, 0f,
                   x , y , z , 1f };
    return m2;
  }
  /**
   * Translate a matrix (this is equivalent to OpenGL glTranslate*).
   * @param m the matrix to translate
   * @param x the x coordinate of the translation vector
   * @param y the y coordinate of the translation vector
   * @param z the z coordinate of the translation vector
   * @return the resulting matrix
   */
  public static float[] matrixTranslate(float[] m, float x, float y, float z) {
    float[] r = new float[16];
    System.arraycopy(m, 0, r, 0, 12);
    r[12] = m[12] + x;
    r[13] = m[13] + y;
    r[14] = m[14] + z;
    r[15] = 1f;
    return r;
    //return matrixMultiply(matrixTranslate(x, y, z), m);
  }
  public static float[] matrixPerspective(float fovy, float aspect, float znear, float zfar) {
    // this code is adapted from Mesa :)
    float xmax, ymax;
    ymax = znear * (float) Math.tan(Math.toRadians(fovy / 2f));
    xmax = aspect * ymax;
    return matrixFrustum(-xmax, xmax, -ymax, ymax, znear, zfar);
  }
  public static float[] matrixFrustum(float left, float right, float bottom, float top, float near, float far) {
    // this code is adapted from Mesa :)
    float x, y, a, b, c, d;
    float[] r = new float[16];
    r[14] = right - left;
    r[10] = top - bottom;
    r[0 ] = 2f * near;
    r[5 ] = r[0] / r[10];
    r[0 ] = r[0] / r[14];
    r[8 ] = (right + left) / r[14];
    r[9 ] = (top + bottom) / r[10];
    r[14] = far - near;
    r[10] = -(far + near) / r[14];
    r[14] = -(2f * far * near) / r[14];  // error ? (this rem was in Mesa)
    r[1 ] = 0f;
    r[2 ] = 0f;
    r[3 ] = 0f;
    r[4 ] = 0f;
    r[6 ] = 0f;
    r[7 ] = 0f;
    r[11] = -1f;
    r[12] = 0f;
    r[13] = 0f;
    r[15] = 0f;
    return r;
  }
}





Conversion between polar and rectangular coordinates

     

strictfp class MainClass {
  public static void main(String[] args) {
    double num, loge, log10, aloge, alog10;
    // Obtain input from user
    num = 0.111d;
    // Calculate and display the natural logarithm
    loge = Math.log(num);
    System.out.println("log base e = " + loge);
    // Calculate the common log
    log10 = Math.log(num) / Math.log(10.0);
    System.out.println("log base 10 = " + log10);
    // Calculate the antilogarithm of log base e
    aloge = Math.exp(loge);
    System.out.println("antilog of log base e = " + aloge);
    // Calculate the antilogarithm of log base 10
    alog10 = Math.pow(10.0, log10);
    System.out.println("anitlog of log base 10 = " + alog10);
  }
}





Demonstrate a few of the Math functions for Trigonometry

     
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
/**
 * Demonstrate a few of the Math functions for Trigonometry.
 * @author Ian F. Darwin, http://www.darwinsys.ru/
 * @version $Id: Trig.java,v 1.5 2004/02/09 03:33:58 ian Exp $
 */
public class Trig {
  public static void main(String[] argv) {
    //+
    System.out.println("Java"s PI is " + Math.PI);
    System.out.println("Java"s e is " + Math.E);
    System.out.println("The cosine of 1.1418 is " + Math.cos(1.1418));
    //-
  }
}





Demonstrate our own version round()

     
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
/**
 * Demonstrate our own version round().
 * @author Ian F. Darwin, http://www.darwinsys.ru/
 * @version $Id: Round.java,v 1.4 2004/03/06 22:17:32 ian Exp $
 */
public class Round {
  /** We round a number up if its fraction exceeds this threshold. */
  public static final double THRESHOLD = 0.54;
  /* 
   * Round floating values to integers.
   * @Return the closest int to the argument.
   * @param d A non-negative values to be rounded.
   */
  static int round(double d) {
    if (d < 0) {
      throw new IllegalArgumentException("Value must be non-negative");
    }
    int di = (int)Math.floor(d);  // integral value below (or ==) d
    if ((d - di) > THRESHOLD) {
      return di + 1;
    } else {
      return di;
    }
  }
  
  public static void main(String[] argv) {
    for (double d = 0.1; d<=1.0; d+=0.01) {
      System.out.println("My way:  " + d + "-> " + round(d));
      System.out.println("Math way:" + d + "-> " + Math.round(d));
    }
  }
}





Exponential Demo

     
/*
 * Copyright (c) 2006 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:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution 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, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
public class ExponentialDemo {
  public static void main(String[] args) {
    double x = 11.635;
    double y = 2.76;
    System.out.println("The value of e is " + Math.E);
    System.out.println("exp(" + x + ") is " + Math.exp(x));
    System.out.println("log(" + x + ") is " + Math.log(x));
    System.out.println("pow(" + x + ", " + y + ") is " + Math.pow(x, y));
    System.out.println("sqrt(" + x + ") is " + Math.sqrt(x));
  }
}





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(70));
    System.out.println(Math.floor(31.1));
    System.out.println(Math.floor(12.5));
    System.out.println(Math.floor(-10));
    System.out.println(Math.floor(-12.4));
    System.out.println(Math.floor(0));
  }
}





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(3.4f, 4.3f));
    System.out.println(Math.max(6.34, 1.45));
    System.out.println(Math.max(4l, 5l));
  }
}





Find minimum of two numbers using Math.min

     
public class Main {
  public static void main(String[] args) {
    System.out.println(Math.min(4, 5));
    System.out.println(Math.min(4.34f, 2.34f));
    System.out.println(Math.min(4.334, 3.342));
    System.out.println(Math.min(123123123123123L, 123123123123123L));
  }
}





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));
  }
}





For a double precision value x, this method returns +1.0 if x >= 0 and -1.0 if x < 0. Returns NaN if x is NaN.

   
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 {
  /**
   * For a double precision value x, this method returns +1.0 if x >= 0 and
   * -1.0 if x < 0. Returns <code>NaN</code> if <code>x</code> is
   * <code>NaN</code>.
   * 
   * @param x the value, a double
   * @return +1.0 or -1.0, depending on the sign of x
   */
  public static double indicator(final double x) {
      if (Double.isNaN(x)) {
          return Double.NaN;
      }
      return (x >= 0.0) ? 1.0 : -1.0;
  }
}





For a float value x, this method returns +1.0F if x >= 0 and -1.0F if x < 0. Returns NaN if x is NaN.

   
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 {
  /**
   * For a float value x, this method returns +1.0F if x >= 0 and -1.0F if x <
   * 0. Returns <code>NaN</code> if <code>x</code> is <code>NaN</code>.
   * 
   * @param x the value, a float
   * @return +1.0F or -1.0F, depending on the sign of x
   */
  public static float indicator(final float x) {
      if (Float.isNaN(x)) {
          return Float.NaN;
      }
      return (x >= 0.0F) ? 1.0F : -1.0F;
  }
}





Gets the greatest common divisor of the absolute value of two numbers

   
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 {
  /**
   * <p>
   * Gets the greatest common divisor of the absolute value of two numbers,
   * using the "binary gcd" method which avoids division and modulo
   * operations. See Knuth 4.5.2 algorithm B. This algorithm is due to Josef
   * Stein (1961).
   * </p>
   * 
   * @param u a non-zero number
   * @param v a non-zero number
   * @return the greatest common divisor, never zero
   * @since 1.1
   */
  public static int gcd(int u, int v) {
      if (u * v == 0) {
          return (Math.abs(u) + Math.abs(v));
      }
      // keep u and v negative, as negative integers range down to
      // -2^31, while positive numbers can only be as large as 2^31-1
      // (i.e. we can"t necessarily negate a negative number without
      // overflow)
      /* assert u!=0 && v!=0; */
      if (u > 0) {
          u = -u;
      } // make u negative
      if (v > 0) {
          v = -v;
      } // make v negative
      // B1. [Find power of 2]
      int k = 0;
      while ((u & 1) == 0 && (v & 1) == 0 && k < 31) { // while u and v are
                                                          // both even...
          u /= 2;
          v /= 2;
          k++; // cast out twos.
      }
      if (k == 31) {
          throw new ArithmeticException("overflow: gcd is 2^31");
      }
      // B2. Initialize: u and v have been divided by 2^k and at least
      // one is odd.
      int t = ((u & 1) == 1) ? v : -(u / 2)/* B3 */;
      // t negative: u was odd, v may be even (t replaces v)
      // t positive: u was even, v is odd (t replaces u)
      do {
          /* assert u<0 && v<0; */
          // B4/B3: cast out twos from t.
          while ((t & 1) == 0) { // while t is even..
              t /= 2; // cast out twos
          }
          // B5 [reset max(u,v)]
          if (t > 0) {
              u = -t;
          } else {
              v = t;
          }
          // B6/B3. at this point both u and v should be odd.
          t = (v - u) / 2;
          // |u| larger: t positive (replace u)
          // |v| larger: t negative (replace v)
      } while (t != 0);
      return -u * (1 << k); // gcd is u*2^k
  }
}





Get the power value

     
public class Power {
  public static void main(String[] args) {
      System.out.println(Math.pow(2, 2));
  }
}





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&euml;l Grosbois and
 * Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel
 * Askel&ouml;f (Ericsson Radio Systems AB); and Bertrand Berthelot, David
 * Bouchard, F&eacute;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&euml;l Grosbois and
 * Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel
 * Askel&ouml;f (Ericsson Radio Systems AB); and Bertrand Berthelot, David
 * Bouchard, F&eacute;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;
  }
}





Make Exponention

    
/*
 * Copyright (c) 2003 - 2007 OpenSubsystems s.r.o. Slovak Republic. All rights reserved.
 * 
 * Project: OpenSubsystems
 * 
 * $Id: NumberUtils.java,v 1.9 2007/01/07 06:14:01 bastafidli Exp $
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2 of the License. 
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
 */
import java.text.NumberFormat;
/**
 * Collection of useful utilities to work with numbers. 
 * 
 * @version $Id: NumberUtils.java,v 1.9 2007/01/07 06:14:01 bastafidli Exp $
 * @author Peter Satury
 * @code.reviewer Miro Halas
 * @code.reviewed Initial revision
 */
public final class NumberUtils
{
   // Constants ////////////////////////////////////////////////////////////////
   
   /**
    * Static array used to append leading 0 chars to file name constructed from
    * number.
    */
   protected static final char[] ZEROCHARS = {"0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
                                              "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
                                              "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
                                              "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
                                              "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
                                             };
   // Cached values ////////////////////////////////////////////////////////////
   
   /**
    * static Number format for no Exponent 
    */
   public static final NumberFormat NFFORMAT;
   
   /**
    * static Number format for no Exponent for editing
    */
   public static final NumberFormat NFFORMATEDIT;
   /**
    * static Number format for Currency
    */
   public static final NumberFormat NFCURRENCYFORMAT;
   /**
    * static Number format for Currency for editing
    */
   public static final NumberFormat NFCURRENCYFORMATEDIT;
   // Constructors /////////////////////////////////////////////////////////////
   
   /**
    * Static initializer.
    */
   static
   {
      
      NFFORMAT = NumberFormat.getNumberInstance();
      NFFORMAT.setMaximumFractionDigits(20);
      
      NFFORMATEDIT = NumberFormat.getNumberInstance();
      NFFORMATEDIT.setMaximumFractionDigits(20);
      NFFORMATEDIT.setGroupingUsed(false);
      NFCURRENCYFORMAT = NumberFormat.getNumberInstance();
      NFCURRENCYFORMAT.setMaximumFractionDigits(2);
      NFCURRENCYFORMAT.setMinimumFractionDigits(2);
      NFCURRENCYFORMATEDIT = NumberFormat.getNumberInstance();
      NFCURRENCYFORMATEDIT.setMaximumFractionDigits(2);
      NFCURRENCYFORMATEDIT.setMinimumFractionDigits(2);
      NFCURRENCYFORMATEDIT.setGroupingUsed(false);
   }
   /** 
    * Private constructor since this class cannot be instantiated
    */
   private NumberUtils(
   )
   {
      // Do nothing
   }
   // Public methods ///////////////////////////////////////////////////////////
   
   /**
    * Method to make Exponention
    * 
    * @param iBbase - base of Exponention [1..]
    * @param iExponent - exponent of Exponention [0..14]
    * @return long - result of Exponention
    * @throws IllegalArgumentException - in case of arguments out of valid range
    */
   public static long exponentiate(
      int iBbase, 
      int iExponent
   ) throws IllegalArgumentException
   {
      if (iExponent > 14 || iExponent < 0)
      {
         throw new IllegalArgumentException(
               "Exponent could not be greater then 14 and lower then 0");
      }
      if (iBbase < 1)
      {
         throw new IllegalArgumentException(
               "Exponentiate base could not be lower then 1");
      }
      long lReturn = 1;
      for (int iCounter = 0; iCounter < iExponent; iCounter++)
      {
         try
         {
            lReturn = lReturn * iBbase;
         } 
         catch (Exception eExc)
         {
            throw new IllegalArgumentException(
                  "Exponentiate arguments too high");
         }
      }
      return lReturn;
   }
   /**
    * Method to make specified length digit number string representation from particular 
    * input number.
    * For example, if there will be send input number 32 and digit lenhth = 8, output 
    * will be string "00000032"
    * 
    * @param iInputNumber - input number that will be converted into 8 digit number 
    *                       string representation
    * @param iDigitLength - length of the output digit number string
    * 
    * @return String - digit number string representation
    */
   public static String getDigitNumberString(
      int iInputNumber,
      int iDigitLength
   )
   {
      StringBuffer idString = new StringBuffer(Integer.toString(iInputNumber));
      
      if (iDigitLength - idString.length() > 0)
      {
         idString.insert(0, ZEROCHARS, 0, iDigitLength - idString.length());
      }
      return idString.toString();
   }
}





Matrix manipulation

  
/**
 * Copyright (c) 2003, www.pdfbox.org
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. 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.
 * 3. Neither the name of pdfbox; 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 REGENTS 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.
 *
 * http://www.pdfbox.org
 *
 */
import java.awt.geom.AffineTransform;
/**
 * This class will be used for matrix manipulation.
 *
 * @author 
 * @version $Revision: 1.14 $
 */
public class Matrix implements Cloneable
{
    private float[] single = 
    { 
        1,0,0,
        0,1,0,
        0,0,1
    };
    /**
     * Constructor.
     */
    public Matrix()
    {
        //default constructor
    }
    
    /**
     * Create an affine transform from this matrix"s values.
     * 
     * @return An affine transform with this matrix"s values.
     */
    public AffineTransform createAffineTransform()
    {
        AffineTransform retval = new AffineTransform(
            single[0], single[1], 
            single[3], single[4],
            single[6], single[7] );
        return retval;
    }
    
    /**
     * Set the values of the matrix from the AffineTransform.
     * 
     * @param af The transform to get the values from.
     */
    public void setFromAffineTransform( AffineTransform af )
    {
        single[0] = (float)af.getScaleX();
        single[1] = (float)af.getShearY();
        single[3] = (float)af.getShearX();
        single[4] = (float)af.getScaleY();
        single[6] = (float)af.getTranslateX();
        single[7] = (float)af.getTranslateY();
    }
    /**
     * This will get a matrix value at some point.
     *
     * @param row The row to get the value from.
     * @param column The column to get the value from.
     *
     * @return The value at the row/column position.
     */
    public float getValue( int row, int column )
    {
        return single[row*3+column];
    }
    /**
     * This will set a value at a position.
     *
     * @param row The row to set the value at.
     * @param column the column to set the value at.
     * @param value The value to set at the position.
     */
    public void setValue( int row, int column, float value )
    {
        single[row*3+column] = value;
    }
    
    /**
     * Return a single dimension array of all values in the matrix.
     * 
     * @return The values ot this matrix.
     */
    public float[][] getValues()
    {
        float[][] retval = new float[3][3];
        retval[0][0] = single[0];
        retval[0][1] = single[1];
        retval[0][2] = single[2];
        retval[1][0] = single[3];
        retval[1][1] = single[4];
        retval[1][2] = single[5];
        retval[2][0] = single[6];
        retval[2][1] = single[7];
        retval[2][2] = single[8];
        return retval;
    }
    
    /**
     * Return a single dimension array of all values in the matrix.
     * 
     * @return The values ot this matrix.
     */
    public double[][] getValuesAsDouble()
    {
        double[][] retval = new double[3][3];
        retval[0][0] = single[0];
        retval[0][1] = single[1];
        retval[0][2] = single[2];
        retval[1][0] = single[3];
        retval[1][1] = single[4];
        retval[1][2] = single[5];
        retval[2][0] = single[6];
        retval[2][1] = single[7];
        retval[2][2] = single[8];
        return retval;
    }
    /**
     * This will take the current matrix and multipy it with a matrix that is passed in.
     *
     * @param b The matrix to multiply by.
     *
     * @return The result of the two multiplied matrices.
     */
    public Matrix multiply( Matrix b )
    {
        Matrix result = new Matrix();
        float[] bMatrix = b.single;
        float[] resultMatrix = result.single;
        resultMatrix[0] = single[0] * bMatrix[0] + single[1] * bMatrix[3] + single[2] * bMatrix[6];
        resultMatrix[1] = single[0] * bMatrix[1] + single[1] * bMatrix[4] + single[2] * bMatrix[7];
        resultMatrix[2] = single[0] * bMatrix[2] + single[1] * bMatrix[5] + single[2] * bMatrix[8];
        resultMatrix[3] = single[3] * bMatrix[0] + single[4] * bMatrix[3] + single[5] * bMatrix[6];
        resultMatrix[4] = single[3] * bMatrix[1] + single[4] * bMatrix[4] + single[5] * bMatrix[7];
        resultMatrix[5] = single[3] * bMatrix[2] + single[4] * bMatrix[5] + single[5] * bMatrix[8];
        resultMatrix[6] = single[6] * bMatrix[0] + single[7] * bMatrix[3] + single[8] * bMatrix[6];
        resultMatrix[7] = single[6] * bMatrix[1] + single[7] * bMatrix[4] + single[8] * bMatrix[7];
        resultMatrix[8] = single[6] * bMatrix[2] + single[7] * bMatrix[5] + single[8] * bMatrix[8];
        return result;
    }
    
    /**
     * Create a new matrix with just the scaling operators.
     * 
     * @return A new matrix with just the scaling operators.
     */
    public Matrix extractScaling()
    {
        Matrix retval = new Matrix();
        
        retval.single[0] = this.single[0];
        retval.single[4] = this.single[4];
        
        return retval;
    }
    
    /**
     * Convenience method to create a scaled instance. 
     * 
     * @param x The xscale operator.
     * @param y The yscale operator.
     * @return A new matrix with just the x/y scaling
     */
    public static Matrix getScaleInstance( float x, float y)
    {
        Matrix retval = new Matrix();
        
        retval.single[0] = x;
        retval.single[4] = y;
        
        return retval;
    }
    
    /**
     * Create a new matrix with just the translating operators.
     * 
     * @return A new matrix with just the translating operators.
     */
    public Matrix extractTranslating()
    {
        Matrix retval = new Matrix();
        
        retval.single[6] = this.single[6];
        retval.single[7] = this.single[7];
        
        return retval;
    }
    
    /**
     * Convenience method to create a translating instance. 
     * 
     * @param x The x translating operator.
     * @param y The y translating operator.
     * @return A new matrix with just the x/y translating.
     */
    public static Matrix getTranslatingInstance( float x, float y)
    {
        Matrix retval = new Matrix();
        
        retval.single[6] = x;
        retval.single[7] = y;
        
        return retval;
    }
    /**
     * Clones this object.
     * @return cloned matrix as an object.
     */
    public Object clone()
    {
        Matrix clone = new Matrix();
        System.arraycopy( single, 0, clone.single, 0, 9 );
        return clone;
    }
    /**
     * This will copy the text matrix data.
     *
     * @return a matrix that matches this one.
     */
    public Matrix copy()
    {
        return (Matrix) clone();
    }
    /**
     * This will return a string representation of the matrix.
     *
     * @return The matrix as a string.
     */
    public String toString()
    {
        StringBuffer result = new StringBuffer( "" );
        result.append( "[[" );
        result.append( single[0] + "," );
        result.append( single[1] + "," );
        result.append( single[2] + "][");
        result.append( single[3] + "," );
        result.append( single[4] + "," );
        result.append( single[5] + "][");
        result.append( single[6] + "," );
        result.append( single[7] + "," );
        result.append( single[8] + "]]");
        
        return result.toString();
    }
    
    /**
     * Get the xscaling factor of this matrix.
     * @return The x-scale.
     */
    public float getXScale()
    {
        float xScale = single[0];
        
        /**
         * BM: if the trm is rotated, the calculation is a little more complicated 
         * 
         * The rotation matrix multiplied with the scaling matrix is:
         * (   x   0   0)    ( cos  sin  0)    ( x*cos x*sin   0)
         * (   0   y   0) *  (-sin  cos  0)  = (-y*sin y*cos   0)
         * (   0   0   1)    (   0    0  1)    (     0     0   1)
         *
         * So, if you want to deduce x from the matrix you take
         * M(0,0) = x*cos and M(0,1) = x*sin and use the theorem of Pythagoras
         * 
         * sqrt(M(0,0)^2+M(0,1)^2) =
         * sqrt(x2*cos2+x2*sin2) =
         * sqrt(x2*(cos2+sin2)) = <- here is the trick cos2+sin2 is one
         * sqrt(x2) =
         * abs(x) 
         */
        if( !(single[1]==0.0f && single[3]==0.0f) )
        {
            xScale = (float)Math.sqrt(Math.pow(single[0], 2)+
                                      Math.pow(single[1], 2));
        } 
        return xScale;
    }
    
    /**
     * Get the y scaling factor of this matrix.
     * @return The y-scale factor.
     */
    public float getYScale()
    {
        float yScale = single[4];
        if( !(single[1]==0.0f && single[3]==0.0f) )
        {
            yScale = (float)Math.sqrt(Math.pow(single[3], 2)+
                                      Math.pow(single[4], 2));
        } 
        return yScale;
    }
    
    /**
     * Get the x position in the matrix.
     * @return The x-position.
     */
    public float getXPosition()
    {
        return single[6];
    }
    
    /**
     * Get the y position.
     * @return The y position.
     */
    public float getYPosition()
    {
        return single[7];
    }
}





Min Demo

     
/*
 * Copyright (c) 2006 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:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution 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, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
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));
  }
}





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 &pi;. */
  private static final double TWO_PI = 2 * Math.PI;
  /**
   * Normalize an angle in a 2&pi wide interval around a center value.
   * <p>This method has three main uses:</p>
   * <ul>
   *   <li>normalize an angle between 0 and 2&pi;:<br/>
   *       <code>a = MathUtils.normalizeAngle(a, Math.PI);</code></li>
   *   <li>normalize an angle between -&pi; and +&pi;<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>
   * <p>Note that due to numerical accuracy and since &pi; 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.</p>
   * @param a angle to normalize
   * @param center center of the desired 2&pi; interval for the result
   * @return a-2k&pi; with integer k and center-&pi; &lt;= a-2k&pi; &lt;= center+&pi;
   * @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 {
  private final static double TWO_PI = 2 * PI;
  /**
   * Normalizes an angle to an absolute angle.
   * The normalized angle will be in the range from 0 to 2*PI, where 2*PI
   * itself is not included.
   *
   * @param angle the angle to normalize
   * @return the normalized angle that will be in the range of [0,2*PI[
   */
  public static double normalAbsoluteAngle(double angle) {
    return (angle %= TWO_PI) >= 0 ? angle : (angle + TWO_PI);
  }
}





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 a double representation 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 a <code>double</code> representation 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.
   * <p>
   * <Strong>Preconditions</strong>:
   * <ul>
   * <li> <code>0 <= k <= n </code> (otherwise
   * <code>IllegalArgumentException</code> is thrown)</li>
   * </ul></p>
   * 
   * @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;
  }
}





Returns an integer hash code representing the given double array 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 {
  /**
   * Returns an integer hash code representing the given double array value.
   * 
   * @param value the value to be hashed (may be null)
   * @return the hash code
   * @since 1.2
   */
  public static int hash(double[] value) {
      if (value == null) {
          return 0;
      }
      int result = value.length;
      for (int i = 0; i < value.length; ++i) {
          result = result * 31 + hash(value[i]);
      }
      return result;
  }
  /**
   * Returns an integer hash code representing the given double value.
   * 
   * @param value the value to be hashed
   * @return the hash code
   */
  public static int hash(double value) {
      long bits = Double.doubleToLongBits(value);
      return (int)(bits ^ (bits >>> 32));
  }
}





Returns an integer hash code representing the given double 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 {
  /**
   * Returns an integer hash code representing the given double value.
   * 
   * @param value the value to be hashed
   * @return the hash code
   */
  public static int hash(double value) {
      long bits = Double.doubleToLongBits(value);
      return (int)(bits ^ (bits >>> 32));
  }
}





Returns exact (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 an exact representation 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.
   * <p>
   * <Strong>Preconditions</strong>:
   * <ul>
   * <li> <code>0 <= k <= n </code> (otherwise
   * <code>IllegalArgumentException</code> is thrown)</li>
   * </ul></p>
   * 
   * @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;
  }
}





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>.
   * <p>
   * <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>
   * </p>
   * 
   * @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!.
   * <p>
   * <Strong>Preconditions</strong>:
   * <ul>
   * <li> <code>n >= 0</code> (otherwise
   * <code>IllegalArgumentException</code> is thrown)</li>
   * </ul></p>
   * 
   * @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>.
   * <p>
   * <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>
   * </p>
   * 
   * @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!.
   * <p>
   * <Strong>Preconditions</strong>:
   * <ul>
   * <li> <code>n >= 0</code> (otherwise
   * <code>IllegalArgumentException</code> is thrown)</li>
   * </ul></p>
   * 
   * @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 least common multiple between two integer values.

   
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 least common multiple between two integer values.
   * 
   * @param a the first integer value.
   * @param b the second integer value.
   * @return the least common multiple between a and b.
   * @throws ArithmeticException if the lcm is too large to store as an int
   * @since 1.1
   */
  public static int lcm(int a, int b) {
      return Math.abs(mulAndCheck(a / gcd(a, b), b));
  }
  /**
   * Multiply two integers, checking for overflow.
   * 
   * @param x a factor
   * @param y a factor
   * @return the product <code>x*y</code>
   * @throws ArithmeticException if the result can not be represented as an
   *         int
   * @since 1.1
   */
  public static int mulAndCheck(int x, int y) {
      long m = ((long)x) * ((long)y);
      if (m < Integer.MIN_VALUE || m > Integer.MAX_VALUE) {
          throw new ArithmeticException("overflow: mul");
      }
      return (int)m;
  }
  /**
   * <p>
   * Gets the greatest common divisor of the absolute value of two numbers,
   * using the "binary gcd" method which avoids division and modulo
   * operations. See Knuth 4.5.2 algorithm B. This algorithm is due to Josef
   * Stein (1961).
   * </p>
   * 
   * @param u a non-zero number
   * @param v a non-zero number
   * @return the greatest common divisor, never zero
   * @since 1.1
   */
  public static int gcd(int u, int v) {
      if (u * v == 0) {
          return (Math.abs(u) + Math.abs(v));
      }
      // keep u and v negative, as negative integers range down to
      // -2^31, while positive numbers can only be as large as 2^31-1
      // (i.e. we can"t necessarily negate a negative number without
      // overflow)
      /* assert u!=0 && v!=0; */
      if (u > 0) {
          u = -u;
      } // make u negative
      if (v > 0) {
          v = -v;
      } // make v negative
      // B1. [Find power of 2]
      int k = 0;
      while ((u & 1) == 0 && (v & 1) == 0 && k < 31) { // while u and v are
                                                          // both even...
          u /= 2;
          v /= 2;
          k++; // cast out twos.
      }
      if (k == 31) {
          throw new ArithmeticException("overflow: gcd is 2^31");
      }
      // B2. Initialize: u and v have been divided by 2^k and at least
      // one is odd.
      int t = ((u & 1) == 1) ? v : -(u / 2)/* B3 */;
      // t negative: u was odd, v may be even (t replaces v)
      // t positive: u was even, v is odd (t replaces u)
      do {
          /* assert u<0 && v<0; */
          // B4/B3: cast out twos from t.
          while ((t & 1) == 0) { // while t is even..
              t /= 2; // cast out twos
          }
          // B5 [reset max(u,v)]
          if (t > 0) {
              u = -t;
          } else {
              v = t;
          }
          // B6/B3. at this point both u and v should be odd.
          t = (v - u) / 2;
          // |u| larger: t positive (replace u)
          // |v| larger: t negative (replace v)
      } while (t != 0);
      return -u * (1 << k); // gcd is u*2^k
  }
}





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!.
   * <p>
   * <Strong>Preconditions</strong>:
   * <ul>
   * <li> <code>n >= 0</code> (otherwise
   * <code>IllegalArgumentException</code> is thrown)</li>
   * </ul></p>
   * 
   * @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.
   * <p>
   * <Strong>Preconditions</strong>:
   * <ul>
   * <li> <code>0 <= k <= n </code> (otherwise
   * <code>IllegalArgumentException</code> is thrown)</li>
   * </ul></p>
   * 
   * @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;
  }
}





Solving right triangles

     
strictfp class TrigSolv {
  public static void main(String[] args) {
    double a, b, c, angleA, radA;
    // Apllying Pythagoras" Theorem
    // Obtain sides from user
    System.out.println("Side c in terms of sides a and b");
    a = 10d;
    b = 20d;
    c = Math.sqrt((a * a) + (b * b));
    System.out.println("Side c = " + c);
    // Using side/angle formula
    System.out.println("Side c in terms of side b and angle A");
    b = 30d;
    angleA = 20d;
    radA = Math.toRadians(angleA);
    c = b * Math.tan(radA);
    System.out.println("Side c = " + c);
  }
}





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;
   }
}





Trigonometric Demo

     
/*
 * Copyright (c) 2006 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:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution 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, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
public class TrigonometricDemo {
  public static void main(String[] args) {
    double degrees = 45.0;
    double radians = Math.toRadians(degrees);
    System.out.println("The value of pi is " + Math.PI);
    System.out.println("The sine of " + degrees + " is "
        + Math.sin(radians));
    System.out.println("The cosine of " + degrees + " is "
        + Math.cos(radians));
    System.out.println("The tangent of " + degrees + " is "
        + Math.tan(radians));
    System.out.println("The arc sine of " + Math.sin(radians) + " is "
        + Math.toDegrees(Math.asin(Math.sin(radians))) + " degrees");
    System.out.println("The arc cosine of " + Math.cos(radians) + " is "
        + Math.toDegrees(Math.acos(Math.cos(radians))) + " degrees");
    System.out.println("The arc tangent of " + Math.tan(radians) + " is "
        + Math.toDegrees(Math.atan(Math.tan(radians))) + " degrees");
  }
}





Using BigDecimal for Precision

     
import java.math.BigDecimal;
public class BigDec {
  public static void main(String args[]) {
    BigDecimal rate = new BigDecimal(".03251234");
    BigDecimal months = new BigDecimal("12");
    BigDecimal monthlyRate = rate
        .divide(months, BigDecimal.ROUND_HALF_DOWN);
    System.out.println("Annual rate : " + rate);
    System.out.println("Monthly rate: " + monthlyRate);
    BigDecimal balance = new BigDecimal("10000.0000");
    for (int i = 0; i < 12; i++) {
      BigDecimal interest = balance.multiply(monthlyRate);
      balance = balance.add(interest);
      System.out.println("Balance: " + balance);
    }
  }
}





Using strict math at the method level

     
strictfp class StrictPI {
  public static void main(String[] args) {
    // Calculate PI^2
    double PI2 = Math.PI * Math.PI;
    System.out.println(PI2);
  }
}





Using strict math in applications

     
public class strictE {
  public static void main(String[] args) {
    // Calculate E^2
    double e2 = StrictMath.E * StrictMath.E;
    System.out.println(e2);
  }
}





Using the Math Trig Methods

     
public class MathTest {
  public static void main(String args[]) {
    int angles[] = { 0, 30, 45, 60, 90, 180 };
    for (int i = 0, n = angles.length; i < n; i++) {
      double rad = Math.toRadians(angles[i]);
      System.out.println("Angle: " + angles[i]);
      System.out.println(" Sine  : " + Math.sin(rad));
      System.out.println(" Cosine : " + Math.cos(rad));
      System.out.println(" Tangent: " + Math.tan(rad));
    }
  }
}





Using the pow() function

     
strictfp class MainClass {
  public static void main(String[] args) {
    // Display the square root of 2 using sqrt()
    System.out.print("sqrt(2.0) = ");
    System.out.println(Math.sqrt(2.0));
    // Calculate and display using pow()
    System.out.print("pow(2.0, 0.5) = ");
    System.out.println(Math.pow(2.0, 0.5));
    System.out.println();
  }
}





Weighted floating-point comparisons

     
class WtComp {
  public static boolean equals(double v1, // First argument
      double v2, // Second argument
      double e) // Epsilon
  {
    return Math.abs(v1 - v2) < e;
  }
  public static void main(String[] args) {
    double a = 9.33333333333000;
    double b = 9.33333333333333;
    final double EPSILON = 1.0E-10;
    if (equals(a, b, EPSILON))
      System.out.println("values are equal");
    else
      System.out.println("values are not equal");
  }
}