Mathematical functions

      Arrays Java Programming
      Mathematical functions
      Large numbers
      Navigate Language Fundamentals topic: v  d  e )

      The java.lang.Math class allows for the use of many common mathematical functions that can be used while creating programs.

      Since it is in the java.lang package, the Math class need not be imported. However, in programs extensively utilizing these functions, a static import can be used.

      Math constants

      There are two constants in the Math class that are fairly accurate approximations of irrational mathematical numbers.

      Math.E

      The Math.E constant, or the base of natural logarithms, represents the value of e, the base of the natural logarithms, about 2.718282.

      Example Code section 3.20: Math.E
      1. public static final double E = 2.718281828459045;
        

      Math.PI

      The Math.PI constant represents the value of pi, the ratio of a circle's circumference to its diameter, about 3.14159265.

      Example Code section 3.21: Math.PI
      1. public static final double PI = 3.141592653589793;
        
      ↑Jump back a section

      Math methods

      Exponential methods

      There are several methods in the Math class that deal with exponential functions.

      Exponentiation

      The power method, double Math.pow(double, double), returns the first parameter to the power of the second parameter. For example, a call to Math.pow(2, 10) will return a value of 1024.

      The double Math.exp(double) method, a special case of pow, returns e to the power of the parameter. In addition, double Math.expm1(double) returns (ex - 1). Both of these methods are more accurate and convenient in these special cases.

      Java also provides special cases of the pow function for square roots and cube roots of doubles, double Math.sqrt(double) and double Math.cbrt(double).

      Logarithms

      Java has no general logarithm function; when needed this can be simulated using the change-of-base theorem.

      double Math.log(double) returns the natural logarithm of the parameter (not the common logarithm, as its name suggests!).

      double Math.log10(double) returns the common (base-10) logarithm of the parameter.

      double Math.log1p(double) returns ln(parameter+1). It is recommended for small values.

      Trigonometric and hyperbolic methods

      The trigonometric methods of the Math class allow users to easily deal with trigonometric functions in programs. All accept only doubles. Please note that all values using these methods are initially passed and returned in radians, not degrees. However, conversions are possible.

      Trigonometric functions

      The three main trigonometric methods are Math.sin(x), Math.cos(x), and Math.tan(x), which are used to find the sine, cosine, and tangent, respectively, of any given number. So, for example, a call to Math.sin(Math.PI/2) would return a value of about 1. Although methods for finding the cosecant, secant, and cotangent are not available, these values can be found by taking the reciprocal of the sine, cosine, and tangent, respectively. For example, the cosecant of pi/2 could be found using 1/Math.sin(Math.PI/2).

      Inverse trigonometric functions

      Java provides inverse counterparts to the trigonometric functions: Math.asin(x), and Math.acos(x), Math.atan(x).

      Hyperbolic functions

      In addition, hyperbolic functions are available: Math.sinh(x), Math.cosh(x), and Math.tanh(x).

      Radian/degree conversion

      To convert between degree and radian measures of angles, two methods are available, Math.toRadians(x) and Math.toDegrees(x). While using Math.toRadians(x), a degrees value must be passed in, and that value in radians (the degree value multiplied by pi/180) will be returned. The Math.toDegrees(x) method takes in a value in radians and the value in degrees (the radian value multiplied by 180/pi) is returned.

      Absolute value: Math.abs

      The absolute value method of the Math class is compatible with the int, long, float, and double types. The data returned is the absolute value of parameter (how far away it is from zero) in the same date type. For example:

      Example Code section 3.22: Math.abs
      1. int result = Math.abs(-3);
        

      In this example, result will contain a value of 3.

      Maximum and minimum values

      These methods are very simple comparing functions. Instead of using if...else statements, one can use the Math.max(x1, x2) and Math.min(x1, x2) methods. The Math.max(x1, x2) simply returns the greater of the two values, while the Math.min(x1, x2) returns the lesser of the two. Acceptable types for these methods include int, long, float, and double.

      ↑Jump back a section

      Functions dealing with floating-point representation

      Java 1.5 and 1.6 introduced several non-mathematical functions specific to the computer floating-point representation of numbers.

      Math.ulp(double) and Math.ulp(float) return an ulp, the smallest value which, when added to the argument, would be recognized as larger than the argument.

      Math.copySign returns the value of the first argument with the sign of the second argument. It can be used to determine the sign of a zero value.

      Math.getExponent returns (as an int) the exponent used to scale the floating-point argument in computer representation.

      ↑Jump back a section

      Rounding number example

      Sometimes, we are not only interested in mathematically correct rounded numbers, but we want that a fixed number of significant digits are always displayed, regardless of the number used. Here is an example program that returns always the correct string. You are invited to modify it such that it does the same and is simpler!

      The constant class contains repeating constants that should exist only once in the code so that to avoid inadvertent changes. (If the one constant is changed inadvertently, it is most likely to be seen, as it is used at several locations.)

      Computer code Code listing 3.20: Common.java
      1. /**
        
      2.  * Class that comprises of common constant values.
        
      3.  */
        
      4. public class Common {
        
      5.     /** Dash or minus constant */
        
      6.     public static final char DASH = '-';
        
      7.     /** The exponent sign in a scientific number, or the capital letter E */
        
      8.     public static final char EXPONENT = 'E';
        
      9.     /** The full stop or period */
        
      10.     public static final char PERIOD = '.';
        
      11.     /** The zero string constant used at several places */
        
      12.     public static final String ZERO = "0";
        
      13. }
        

      The Maths class is like an addition to the java.lang.Math class and contains the rounding calculations.

      Computer code Code listing 3.21: Maths.java
      1. package common;
        
      2.  
        
      3. /**
        
      4.  * Class for special mathematical calculations.
        
      5.  * ATTENTION: Should not depend on any other class except Java libraries!
        
      6.  */
        
      7. public class Maths {
        
      8.     /** Value after which the language switches from scientific to double */
        
      9.     private final static double E_TO_DOUBLE = 1E-3;
        
      10.  
        
      11.     /** The string of zeros */
        
      12.     private final static String strZEROS = "000000000000000000000000000000000";
        
      13.  
        
      14.     /**
        
      15.      * Determines how many zeros are to be appended after the decimal digits.
        
      16.      * @param SIGNIFICANTS_AFTER Requested significant digits after decimal
        
      17.      * @param SEPARATOR Language-specific decimal separator
        
      18.      * @param SIGNIFICANT_DIGITS Number of all significant digits
        
      19.      * @param NUMBER Rounded number
        
      20.      * @return Requested value
        
      21.      */
        
      22.     private static byte calculateMissingSignificantZeros(
        
      23.             final byte SIGNIFICANTS_AFTER,
        
      24.             final char SEPARATOR,
        
      25.             final double NUMBER) {
        
      26.         final byte AFTER = findSignificantsAfterDecimal(SEPARATOR, NUMBER);
        
      27.  
        
      28.         final byte ZEROS = (byte) (SIGNIFICANTS_AFTER
        
      29.                 - ((AFTER == 0) ? 1 : AFTER));
        
      30.  
        
      31.         return ((ZEROS >= 0) ? ZEROS : 0);
        
      32.     }
        
      33.  
        
      34.     /**
        
      35.      * Calculates the number of all significant digits (without the sign and
        
      36.      * the decimal separator).
        
      37.      * @param SIGNIFICANTS_AFTER Requested significant digits after decimal
        
      38.      * @param SEPARATOR Language-specific decimal separator
        
      39.      * @param NUMBER Value where the digits are to be counted
        
      40.      * @return Number of significant digits
        
      41.      */
        
      42.     private static byte findSignificantDigits(final byte SIGNIFICANTS_AFTER,
        
      43.             final char SEPARATOR,
        
      44.             final double NUMBER) {
        
      45.         if (NUMBER == 0) return 0;
        
      46.         else {
        
      47.             String mantissa =
        
      48.                     findMantissa(SEPARATOR, new Double(NUMBER).toString());
        
      49.  
        
      50.             if (NUMBER == (long)NUMBER) {
        
      51.                 mantissa = mantissa.substring(0, mantissa.length() - 1);
        
      52.             }
        
      53.  
        
      54.             mantissa = RetrieveDigits(SEPARATOR, mantissa);
        
      55.             // Find the position of the first non-zero digit:
        
      56.             short nonZeroAt = 0;
        
      57.  
        
      58.             for (; (nonZeroAt < mantissa.length())
        
      59.                     && (mantissa.charAt(nonZeroAt) == '0'); nonZeroAt++) ;
        
      60.  
        
      61.             return (byte)mantissa.substring(nonZeroAt).length();
        
      62.         }
        
      63.     }
        
      64.  
        
      65.     /**
        
      66.      * Determines the number of significant digits after the decimal separator
        
      67.      * knowing the total number of significant digits and the number before the
        
      68.      * decimal separator.
        
      69.      * @param SIGNIFICANTS_BEFORE Number of significant digits before separator
        
      70.      * @param SIGNIFICANT_DIGITS Number of all significant digits
        
      71.      * @return Number of significant decimals after the separator
        
      72.      */
        
      73.     private static byte findSignificantsAfterDecimal(
        
      74.             final byte SIGNIFICANTS_BEFORE,
        
      75.             final byte SIGNIFICANT_DIGITS) {
        
      76.         final byte AFTER_DECIMAL =
        
      77.                 (byte)(SIGNIFICANT_DIGITS - SIGNIFICANTS_BEFORE);
        
      78.  
        
      79.         return (byte)((AFTER_DECIMAL > 0) ? AFTER_DECIMAL : 0);
        
      80.     }
        
      81.  
        
      82.     /**
        
      83.      * Finds the significant digits after the decimal separator of a mantissa.
        
      84.      * @param SEPARATOR Language-specific decimal separator
        
      85.      * @param NUMBER Value to be scrutinised
        
      86.      * @return Number of significant zeros after decimal separator.
        
      87.      */
        
      88.     public static byte findSignificantsAfterDecimal(final char SEPARATOR,
        
      89.             final double NUMBER) {
        
      90.         if (NUMBER == 0) return 1;
        
      91.         else {
        
      92.             String value = (new Double(NUMBER)).toString();
        
      93.  
        
      94.             final short SEPARATOR_AT = (short) value.indexOf(SEPARATOR);
        
      95.  
        
      96.             if (SEPARATOR_AT > -1) {
        
      97.                 value = value.substring(SEPARATOR_AT + 1);
        
      98.             }
        
      99.  
        
      100.             final short E_AT = (short) value.indexOf(Common.EXPONENT);
        
      101.  
        
      102.             if (E_AT > 0) value = value.substring(0, E_AT);
        
      103.  
        
      104.             Long longValue = new Long(value).longValue();
        
      105.  
        
      106.             if (Math.abs(NUMBER) < 1) {
        
      107.                 return (byte) longValue.toString().length();
        
      108.             } else if (longValue == 0) return 0;
        
      109.             else {
        
      110.                 value = "0." + value;
        
      111.  
        
      112.                 return (byte) (value.length() - 2);
        
      113.             }
        
      114.         }
        
      115.     }
        
      116.  
        
      117.     /**
        
      118.      * Determines the number of digits before the decimal point.
        
      119.      * @param SEPARATOR Language-specific decimal separator
        
      120.      * @param NUMBER Value to be scrutinised
        
      121.      * @return Number of digits before the decimal separator
        
      122.      */
        
      123.     private static byte findSignificantsBeforeDecimal(final char SEPARATOR,
        
      124.             final double NUMBER) {
        
      125.         final String VALUE = new Double(NUMBER).toString();
        
      126.  
        
      127.         // Return immediately, if result is clear: Special handling at
        
      128.         // crossroads of floating point and exponential numbers:
        
      129.         if ((NUMBER == 0) || (Math.abs(NUMBER) >= E_TO_DOUBLE)
        
      130.                 && (Math.abs(NUMBER) < 1)) {
        
      131.             return 0;
        
      132.         }
        
      133.         else if ((Math.abs(NUMBER) > 0) && (Math.abs(NUMBER) < E_TO_DOUBLE)) {
        
      134.             return 1;
        
      135.         }
        
      136.         else {
        
      137.             byte significants = 0;
        
      138.             // Significant digits to the right of decimal separator:
        
      139.             for (byte y = 0; y < VALUE.length(); y++) {
        
      140.                 if (VALUE.charAt(y) == SEPARATOR) break;
        
      141.                 else if (VALUE.charAt(y) != Common.DASH) significants++;
        
      142.             }
        
      143.  
        
      144.             return significants;
        
      145.         }
        
      146.     }
        
      147.  
        
      148.     /**
        
      149.      * Returns the exponent part of the double number.
        
      150.      * @param NUMBER Value of which the exponent is of interest
        
      151.      * @return Exponent of the number or zero.
        
      152.      */
        
      153.     private static short findExponent(final double NUMBER) {
        
      154.         return new Short(findExponent((new Double(NUMBER)).toString()));
        
      155.     }
        
      156.  
        
      157.     /**
        
      158.      * Finds the exponent of a number.
        
      159.      * @param VALUE Value where an exponent is to be searched
        
      160.      * @return Exponent, if it exists, or "0".
        
      161.      */
        
      162.     private static String findExponent(final String VALUE) {
        
      163.         final short E_AT = (short) VALUE.indexOf(Common.EXPONENT);
        
      164.  
        
      165.         if (E_AT < 0) return Common.ZERO;
        
      166.         else return VALUE.substring(E_AT + 1);
        
      167.     }
        
      168.  
        
      169.     /**
        
      170.      * Finds the mantissa of a number.
        
      171.      * @param SEPARATOR Language-specific decimal separator
        
      172.      * @param VALUE Value where the mantissa is to be found
        
      173.      * @return Mantissa of the number
        
      174.      */
        
      175.     private static String findMantissa(final char SEPARATOR,
        
      176.             final String VALUE) {
        
      177.         String value = VALUE;
        
      178.         final short E_AT = (short) value.indexOf(Common.EXPONENT);
        
      179.  
        
      180.         if (E_AT > -1) value = value.substring(0, E_AT);
        
      181.  
        
      182.         return value;
        
      183.     }
        
      184.  
        
      185.     /**
        
      186.      * Retrieves the digits of the value without decimal separator or sign.
        
      187.      * @param SEPARATOR
        
      188.      * @param number Mantissa to be scrutinised
        
      189.      * @return The digits only
        
      190.      */
        
      191.     private static String RetrieveDigits(final char SEPARATOR,
        
      192.             String number) {
        
      193.         // Strip off exponent part, if it exists:
        
      194.         short eAt = (short)number.indexOf(Common.EXPONENT);
        
      195.  
        
      196.         if (eAt > -1) number = number.substring(0, eAt);
        
      197.  
        
      198.         return number.replace((new Character(Common.DASH)).toString(), "").
        
      199.                 replace((new Character(SEPARATOR)).toString(), "");
        
      200.     }
        
      201.  
        
      202.     /**
        
      203.      * Rounds a number to the decimal places.
        
      204.      * @param SIGNIFICANTS_AFTER Requested significant digits after decimal
        
      205.      * @param SEPARATOR Language-specific decimal separator
        
      206.      * @param NUMBER Number to be rounded
        
      207.      * @return Rounded number to the requested decimal places
        
      208.      */
        
      209.     public static double round(final byte SIGNIFICANTS_AFTER,
        
      210.             final char SEPARATOR,
        
      211.             final double NUMBER) {
        
      212.         if (NUMBER == 0) return 0;
        
      213.         else {
        
      214.             final double CONSTANT = power(10, (short)
        
      215.                     (FindInsignificantZerosAfterDecimal(SEPARATOR, NUMBER)
        
      216.                             + SIGNIFICANTS_AFTER));
        
      217.             final short D_EXPONENT = findExponent(NUMBER);
        
      218.  
        
      219.             short exponent = D_EXPONENT;
        
      220.  
        
      221.             double value = NUMBER*CONSTANT*Math.pow(10, -exponent);
        
      222.             final String EXPONENT_SIGN =
        
      223.                     (exponent < 0) ? String.valueOf(Common.DASH) : "";
        
      224.  
        
      225.             if (exponent != 0) {
        
      226.                 exponent = (short) Math.abs(exponent);
        
      227.  
        
      228.                 value = round(value);
        
      229.             } else value = round(value)/CONSTANT;
        
      230.  
        
      231.             // Power method cannot be used, as the exponentiated number may
        
      232.             // exceed the maximal long value.
        
      233.             exponent -= Math.signum(D_EXPONENT)*(findSignificantDigits
        
      234.                     (SIGNIFICANTS_AFTER, SEPARATOR, value) - 1);
        
      235.  
        
      236.             if (D_EXPONENT != 0) {
        
      237.                 String strValue = Double.toString(value);
        
      238.  
        
      239.                 strValue = strValue.substring(0, strValue.indexOf(SEPARATOR))
        
      240.                         + Common.EXPONENT + EXPONENT_SIGN
        
      241.                         + Short.toString(exponent);
        
      242.  
        
      243.                 value = new Double(strValue);
        
      244.             }
        
      245.  
        
      246.             return value;
        
      247.         }
        
      248.     }
        
      249.  
        
      250.     /**
        
      251.      * @param SEPARATOR Language-specific decimal separator
        
      252.      * @param NUMBER
        
      253.      * @return
        
      254.      */
        
      255.     private static byte FindInsignificantZerosAfterDecimal(
        
      256.             final char SEPARATOR,
        
      257.             final double NUMBER) {
        
      258.         if ((Math.abs(NUMBER) >= 1) || isScientific(NUMBER)) return 0;
        
      259.         else {
        
      260.             final StringBuilder STRING = new StringBuilder();
        
      261.  
        
      262.             STRING.append(NUMBER);
        
      263.             STRING.delete(0,
        
      264.                     STRING.indexOf(new Character(SEPARATOR).toString()) + 1);
        
      265.  
        
      266.             // Determine what to match:
        
      267.             final String REGEX = "[1-9]";
        
      268.  
        
      269.             final String[] SPLIT = STRING.toString().split(REGEX);
        
      270.  
        
      271.             return (SPLIT.length > 0) ? (byte) SPLIT[0].length() : 0;
        
      272.         }
        
      273.     }
        
      274.  
        
      275.     /**
        
      276.      * Determines, if the number uses a scientific representation.
        
      277.      * @param NUMBER
        
      278.      * @return true, if it is a scientific number, false otherwise
        
      279.      */
        
      280.     private static boolean isScientific(final double NUMBER) {
        
      281.         return ((new Double(NUMBER)).toString().indexOf(Common.EXPONENT) > 0);
        
      282.     }
        
      283.  
        
      284.     /**
        
      285.      * Rounds a number according to mathematical rules.
        
      286.      * @param VALUE
        
      287.      * @return
        
      288.      */
        
      289.     public static double round(final double VALUE) {
        
      290.         return (long)(VALUE + .5);
        
      291.     }
        
      292.  
        
      293.  
        
      294.     /**
        
      295.      * Calculates the power of the base to the exponent without changing the
        
      296.      * least-significant digits of a number.
        
      297.      * @param BASIS
        
      298.      * @param EXPONENT
        
      299.      * @return BASIS to power of EXPONENT
        
      300.      */
        
      301.     public static double power(final int BASIS, final short EXPONENT) {
        
      302.         return power((short)BASIS, EXPONENT);
        
      303.     }
        
      304.  
        
      305.     /**
        
      306.      * Calculates the power of the base to the exponent without changing the
        
      307.      * least-significant digits of a number.
        
      308.      * @param BASIS
        
      309.      * @param EXPONENT
        
      310.      * @return BASIS to power of EXPONENT
        
      311.      */
        
      312.     public static double power(final short BASIS, final short EXPONENT) {
        
      313.         if (BASIS == 0) return (EXPONENT != 0) ? 1 : 0;
        
      314.         else {
        
      315.             if (EXPONENT == 0) return 1;
        
      316.             else {
        
      317.                 // The Math method power does change the least significant
        
      318.                 // digits after the decimal separator and is therefore useless.
        
      319.                 double result = 1;
        
      320.                 short s = 0;
        
      321.  
        
      322.                 if (EXPONENT > 0) {
        
      323.                     for (; s < EXPONENT; s++) result *= BASIS;
        
      324.                 }
        
      325.                 else if (EXPONENT < 0) {
        
      326.                     for (s = EXPONENT; s < 0; s++) result /= BASIS;
        
      327.                 }
        
      328.  
        
      329.                 return result;
        
      330.             }
        
      331.         }
        
      332.     }
        
      333.  
        
      334.     /**
        
      335.      * Rounds to a fixed number of significant digits.
        
      336.      * @param SIGNIFICANT_DIGITS Requested number of significant digits
        
      337.      * @param SEPARATOR Language-specific decimal separator
        
      338.      * @param dNumber Number to be rounded
        
      339.      * @return Rounded number
        
      340.      */
        
      341.     public static String roundToString(final byte SIGNIFICANT_DIGITS,
        
      342.             final char SEPARATOR,
        
      343.             double dNumber) {
        
      344.         // Number of significants that *are* before the decimal separator:
        
      345.         final byte SIGNIFICANTS_BEFORE =
        
      346.             findSignificantsBeforeDecimal(SEPARATOR, dNumber);
        
      347.         // Number of decimals that *should* be after the decimal separator:
        
      348.         final byte SIGNIFICANTS_AFTER = findSignificantsAfterDecimal(
        
      349.                 SIGNIFICANTS_BEFORE, SIGNIFICANT_DIGITS);
        
      350.         // Round to the specified number of digits after decimal separator:
        
      351.         final double ROUNDED =  Maths.round(SIGNIFICANTS_AFTER, SEPARATOR, dNumber);
        
      352.  
        
      353.         final String EXPONENT = findExponent((new Double(ROUNDED)).toString());
        
      354.         final String MANTISSA = findMantissa(SEPARATOR,
        
      355.                         (new Double(ROUNDED)).toString());
        
      356.  
        
      357.         final double dMANTISSA = new Double(MANTISSA).doubleValue();
        
      358.         final StringBuilder RESULT = new StringBuilder(MANTISSA);
        
      359.         // Determine the significant digits in this number:
        
      360.         final byte SIGNIFICANTS = findSignificantDigits(SIGNIFICANTS_AFTER,
        
      361.                 SEPARATOR, dMANTISSA);
        
      362.         // Add lagging zeros, if necessary:
        
      363.         if (SIGNIFICANTS <= SIGNIFICANT_DIGITS) {
        
      364.             if (SIGNIFICANTS_AFTER != 0) {
        
      365.                 RESULT.append(strZEROS.substring(0,
        
      366.                         calculateMissingSignificantZeros(SIGNIFICANTS_AFTER,
        
      367.                                 SEPARATOR, dMANTISSA)));
        
      368.             } else {
        
      369.                 // Cut off the decimal separator & after decimal digits:
        
      370.                 final short DECIMAL = (short) RESULT.indexOf(
        
      371.                         new Character(SEPARATOR).toString());
        
      372.  
        
      373.                 if (DECIMAL > -1) RESULT.setLength(DECIMAL);
        
      374.             }
        
      375.         } else if (SIGNIFICANTS_BEFORE > SIGNIFICANT_DIGITS) {
        
      376.             dNumber /= power(10, (short)(SIGNIFICANTS_BEFORE - SIGNIFICANT_DIGITS));
        
      377.  
        
      378.             dNumber = round(dNumber);
        
      379.  
        
      380.             final short DIGITS =
        
      381.                     (short)(SIGNIFICANT_DIGITS + ((dNumber < 0) ? 1 : 0));
        
      382.  
        
      383.             String D_VALUE = (new Double(dNumber)).toString().substring(0, DIGITS);
        
      384.  
        
      385.             RESULT.setLength(0);
        
      386.             RESULT.append(D_VALUE + strZEROS.substring(0,
        
      387.                     SIGNIFICANTS_BEFORE - SIGNIFICANT_DIGITS));
        
      388.         }
        
      389.  
        
      390.         if (new Short(EXPONENT) != 0) {
        
      391.             RESULT.append(Common.EXPONENT + EXPONENT);
        
      392.         }
        
      393.  
        
      394.         return RESULT.toString();
        
      395.     } // public static String roundToString(…)
        
      396.  
        
      397.     /**
        
      398.      * Rounds to a fixed number of significant digits.
        
      399.      * @param SEPARATOR Language-specific decimal separator
        
      400.      * @param SIGNIFICANT_DIGITS Requested number of significant digits
        
      401.      * @param value Number to be rounded
        
      402.      * @return Rounded number
        
      403.      */
        
      404.     public static String roundToString(final char SEPARATOR,
        
      405.             final int SIGNIFICANT_DIGITS,
        
      406.             float value) {
        
      407.         return roundToString((byte)SIGNIFICANT_DIGITS, SEPARATOR,
        
      408.                 (double)value);
        
      409.     }
        
      410. } // class Maths
        

      The test class checks all possibilities:

      Computer code Code listing 3.22: TestCommon.java
      1. package common;
        
      2.  
        
      3. import java.util.Vector;
        
      4.  
        
      5. /**
        
      6.  * Test class for the common functionality
        
      7.  * @author Saban
        
      8.  */
        
      9. public class TestCommon {
        
      10.  
        
      11.     /**
        
      12.      * Test for the common functionality
        
      13.      * @param args
        
      14.      */
        
      15.     public static void main(String[] args) {
        
      16.         // Test rounding
        
      17.         Vector<Double> values = new Vector<Double>();
        
      18.  
        
      19.         values.add(0.0);
        
      20.         AddValue(1.4012984643248202e-45, values);
        
      21.         AddValue(1.999999757e-5, values);
        
      22.         AddValue(1.999999757e-4, values);
        
      23.         AddValue(1.999999757e-3, values);
        
      24.         AddValue(0.000640589, values);
        
      25.         AddValue(0.3396899998188019, values);
        
      26.         AddValue(0.34, values);
        
      27.         AddValue(7.07, values);
        
      28.         AddValue(118.188, values);
        
      29.         AddValue(118.2, values);
        
      30.         AddValue(123.405009, values);
        
      31.         AddValue(30.76994323730469, values);
        
      32.         AddValue(130.76994323730469, values);
        
      33.         AddValue(540, values);
        
      34.         AddValue(12345, values);
        
      35.         AddValue(123456, values);
        
      36.         AddValue(540911, values);
        
      37.         AddValue(9.223372036854776e56, values);
        
      38.  
        
      39.         final byte SIGNIFICANTS = 5;
        
      40.  
        
      41.         for (double element : values) {
        
      42.             System.out.println(" Maths.Round(" + SIGNIFICANTS  + ", '"
        
      43.                     + Common.PERIOD + "', " + element + ") = "
        
      44.                     +  Maths.roundToString(SIGNIFICANTS,
        
      45.                             Common.PERIOD, element));
        
      46.         }
        
      47.     }    // void main(String[] args)
        
      48.  
        
      49.     /**
        
      50.      * Method that adds a negative and a positive value to values.
        
      51.      * @param D
        
      52.      * @param values
        
      53.      */
        
      54.     private static void AddValue(final double D, Vector<Double> values) {
        
      55.         values.add(-D);
        
      56.         values.add(D);
        
      57.     }
        
      58. }    // class TestCommon
        
      Computer code Output for code listing 3.22
      Maths.Round(5, '.', 0.0) = 0.00000
      Maths.Round(5, '.', -1.4012984643248202E-45) = -1.4012E-45
      Maths.Round(5, '.', 1.4012984643248202E-45) = 1.4013E-45
      Maths.Round(5, '.', -1.999999757E-5) = -1.9999E-5
      Maths.Round(5, '.', 1.999999757E-5) = 2.0000E-5
      Maths.Round(5, '.', -1.999999757E-4) = -1.9999E-4
      Maths.Round(5, '.', 1.999999757E-4) = 2.0000E-4
      Maths.Round(5, '.', -0.001999999757) = -0.0019999
      Maths.Round(5, '.', 0.001999999757) = 0.0020000
      Maths.Round(5, '.', -6.40589E-4) = -6.4058E-4
      Maths.Round(5, '.', 6.40589E-4) = 6.4059E-4
      Maths.Round(5, '.', -0.3396899998188019) = -0.33968
      Maths.Round(5, '.', 0.3396899998188019) = 0.33969
      Maths.Round(5, '.', -0.34) = -0.33999
      Maths.Round(5, '.', 0.34) = 0.34000
      Maths.Round(5, '.', -7.07) = -7.0699
      Maths.Round(5, '.', 7.07) = 7.0700
      Maths.Round(5, '.', -118.188) = -118.18
      Maths.Round(5, '.', 118.188) = 118.19
      Maths.Round(5, '.', -118.2) = -118.19
      Maths.Round(5, '.', 118.2) = 118.20
      Maths.Round(5, '.', -123.405009) = -123.40
      Maths.Round(5, '.', 123.405009) = 123.41
      Maths.Round(5, '.', -30.76994323730469) = -30.769
      Maths.Round(5, '.', 30.76994323730469) = 30.770
      Maths.Round(5, '.', -130.7699432373047) = -130.76
      Maths.Round(5, '.', 130.7699432373047) = 130.77
      Maths.Round(5, '.', -540.0) = -539.99
      Maths.Round(5, '.', 540.0) = 540.00
      Maths.Round(5, '.', -12345.0) = -12344
      Maths.Round(5, '.', 12345.0) = 12345
      Maths.Round(5, '.', -123456.0) = -123450
      Maths.Round(5, '.', 123456.0) = 123460
      Maths.Round(5, '.', -540911.0) = -540900
      Maths.Round(5, '.', 540911.0) = 540910
      Maths.Round(5, '.', -9.223372036854776E56) = -9.2233E56
      Maths.Round(5, '.', 9.223372036854776E56) = 9.2234E56
      

      If you are interested in a comparison with C#, take a look at the rounding number example there. If you are interested in a comparison with C++, you can compare this code here with the same example over there.

      Notice that in the expression starting with if ((D == 0), I have to use OR instead of the || because of a bug in the source template.

      Clipboard

      To do:
      Add some exercises like the ones in Variables

      Arrays Java Programming
      Mathematical functions
      Large numbers
      ↑Jump back a section
      Last modified on 22 May 2013, at 13:06