Mathematical functions
Navigate Language Fundamentals topic: ) |
The java.lang.Math
class allows 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 does not need to be imported. However, in programs extensively utilizing these functions, a static import can be used.
Math constants
editThere are two constants in the Math
class that are fairly accurate approximations of irrational mathematical numbers.
Math.E
editThe Math.E
constant represents the value of Euler's number (e), the base of the natural logarithm.
Code section 3.20: Math.E
public static final double E = 2.718281828459045;
|
Math.PI
editThe Math.PI
constant represents the value of pi, the ratio of a circle's circumference to its diameter.
Code section 3.21: Math.PI
public static final double PI = 3.141592653589793;
|
Math methods
editExponential methods
editThere are several methods in the Math
class that deal with exponential functions.
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 (210).
The 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
editJava has no general logarithm function; when needed this can be simulated using the change-of-base theorem.
returns the natural logarithm of the parameter (not the common logarithm, as its name suggests!).
double
Math.log(double
)
returns the common (base-10) logarithm of the parameter.
double
Math.log10(double
)
returns ln(parameter+1). It is recommended for small values.
double
Math.log1p(double
)
Trigonometric and hyperbolic methods
editThe trigonometric methods of the Math
class allow users to easily deal with trigonometric functions in programs. All accept only double
s. Please note that all values using these methods are initially passed and returned in radians, not degrees. However, conversions are possible.
Trigonometric functions
editThe 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
editJava provides inverse counterparts to the trigonometric functions: Math.asin(x)
, and Math.acos(x)
, Math.atan(x)
.
Hyperbolic functions
editIn addition, hyperbolic functions are available: Math.sinh(x)
, Math.cosh(x)
, and Math.tanh(x)
.
Radian/degree conversion
editTo 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
edit
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 data type. For example:
Code section 3.22: Math.abs
int result = Math.abs(-3);
|
In this example, result
will contain a value of 3.
Maximum and minimum values
editThese 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
.
Functions dealing with floating-point representation
editJava 1.5 and 1.6 introduced several non-mathematical functions specific to the computer floating-point representation of numbers.
Math.ulp(
and double
)Math.ulp(
return an ulp, the smallest value which, when added to the argument, would be recognized as larger than the argument.
float
)
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.
Rounding number example
editSometimes, 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.)
Code listing 3.20: StringUtils.java
/**
* Class that comprises of constant values & string utilities.
*
* @since 2013-09-05
* @version 2014-10-14
*/
public class StringUtils {
/** Dash or minus constant */
public static final char DASH = '-';
/** The exponent sign in a scientific number, or the capital letter E */
public static final char EXPONENT = 'E';
/** The full stop or period */
public static final char PERIOD = '.';
/** The zero string constant used at several places */
public static final String ZERO = "0";
/**
* Removes all occurrences of the filter character in the text.
*
* @param text Text to be filtered
* @param filter The character to be removed.
* @return the string
*/
public static String filter(final String text, final String filter) {
final String[] words = text.split("[" + filter + "]");
switch (words.length) {
case 0: return text;
case 1: return words[0];
default:
final StringBuilder filteredText = new StringBuilder();
for (final String word : words) {
filteredText.append(word);
}
return filteredText.toString();
}
}
}
|
The MathsUtils class is like an addition to the java.lang.Math
class and contains the rounding calculations.
Code listing 3.21: MathsUtils.java
package string;
/**
* Class for special mathematical calculations.<br/>
* ATTENTION:<br/>Should depend only on standard Java libraries!
*
* @since 2013-09-05
* @version 2014-10-14
*/
public class MathsUtils {
// CONSTANTS
// ------------------------------------------
/** The exponent sign in a scientific number, or the capital letter E. */
public static final char EXPONENT = 'E';
/** Value after which the language switches from scientific to double */
private static final double E_TO_DOUBLE = 1E-3;
/** The zero string constant used at several places. */
public static final String ZERO = "0";
/** The string of zeros */
private static final String ZEROS = "000000000000000000000000000000000";
// METHODS
// ------------------------------------------
/**
* Determines, if the number uses a scientific representation.
*
* @param number the number
* @return true, if it is a scientific number, false otherwise
*/
private static boolean isScientific(final double number) {
return ((new Double(number)).toString().indexOf(EXPONENT) > 0);
}
/**
* Determines how many zeros are to be appended after the decimal digits.
*
* @param significantsAfter Requested significant digits after decimal
* @param separator Language-specific decimal separator
* @param number Rounded number
* @return Requested value
*/
private static byte calculateMissingSignificantZeros(
final byte significantsAfter,
final char separator,
final double number) {
final byte after = findSignificantsAfterDecimal(separator, number);
final byte zeros =
(byte) (significantsAfter - ((after == 0) ? 1 : after));
return ((zeros >= 0) ? zeros : 0);
}
/**
* Finds the insignificant zeros after the decimal separator.
*
* @param separator Language-specific decimal separator
* @param number the number
* @return the byte
*/
private static byte findInsignificantZerosAfterDecimal(
final char separator,
final double number) {
if ((Math.abs(number) >= 1) || isScientific(number)) {
return 0;
} else {
final StringBuilder string = new StringBuilder();
string.append(number);
string.delete(0,
string.indexOf(new Character(separator).toString()) + 1);
// Determine what to match:
final String regularExpression = "[1-9]";
final String[] split = string.toString().split(regularExpression);
return (split.length > 0) ? (byte) split[0].length() : 0;
}
}
/**
* Calculates the number of all significant digits (without the sign and
* the decimal separator).
*
* @param significantsAfter Requested significant digits after decimal
* @param separator Language-specific decimal separator
* @param number Value where the digits are to be counted
* @return Number of significant digits
*/
private static byte findSignificantDigits(final byte significantsAfter,
final char separator,
final double number) {
if (number == 0) { return 0; }
else {
String mantissa =
findMantissa(separator, new Double(number).toString());
if (number == (long)number) {
mantissa = mantissa.substring(0, mantissa.length() - 1);
}
mantissa = retrieveDigits(separator, mantissa);
// Find the position of the first non-zero digit:
short nonZeroAt = 0;
for (; (nonZeroAt < mantissa.length())
&& (mantissa.charAt(nonZeroAt) == '0'); nonZeroAt++) ;
return (byte)mantissa.substring(nonZeroAt).length();
}
}
/**
* Determines the number of significant digits after the decimal separator
* knowing the total number of significant digits and the number before the
* decimal separator.
*
* @param significantsBefore Number of significant digits before separator
* @param significantDigits Number of all significant digits
* @return Number of significant decimals after the separator
*/
private static byte findSignificantsAfterDecimal(
final byte significantsBefore,
final byte significantDigits) {
final byte afterDecimal =
(byte) (significantDigits - significantsBefore);
return (byte) ((afterDecimal > 0) ? afterDecimal : 0);
}
/**
* Determines the number of digits before the decimal point.
*
* @param separator Language-specific decimal separator
* @param number Value to be scrutinised
* @return Number of digits before the decimal separator
*/
private static byte findSignificantsBeforeDecimal(final char separator,
final double number) {
final String value = new Double(number).toString();
// Return immediately, if result is clear: Special handling at
// crossroads of floating point and exponential numbers:
if ((number == 0) || (Math.abs(number) >= E_TO_DOUBLE)
&& (Math.abs(number) < 1)) {
return 0;
} else if ((Math.abs(number) > 0) && (Math.abs(number) < E_TO_DOUBLE)) {
return 1;
} else {
byte significants = 0;
// Significant digits to the right of decimal separator:
for (byte b = 0; b < value.length(); b++) {
if (value.charAt(b) == separator) {
break;
} else if (value.charAt(b) != StringUtils.DASH) {
significants++;
}
}
return significants;
}
}
/**
* Returns the exponent part of the double number.
*
* @param number Value of which the exponent is of interest
* @return Exponent of the number or zero.
*/
private static short findExponent(final double number) {
return new Short(findExponent((new Double(number)).toString()));
}
/**
* Finds the exponent of a number.
*
* @param value Value where an exponent is to be searched
* @return Exponent, if it exists, or "0".
*/
private static String findExponent(final String value) {
final short exponentAt = (short) value.indexOf(EXPONENT);
if (exponentAt < 0) { return ZERO; }
else {
return value.substring(exponentAt + 1);
}
}
/**
* Finds the mantissa of a number.
*
* @param separator Language-specific decimal separator
* @param value Value where the mantissa is to be found
* @return Mantissa of the number
*/
private static String findMantissa(final char separator,
final String value) {
String strValue = value;
final short exponentAt = (short) strValue.indexOf(EXPONENT);
if (exponentAt > -1) {
strValue = strValue.substring(0, exponentAt);
}
return strValue;
}
/**
* Retrieves the digits of the value without decimal separator or sign.
*
* @param separator
* @param number Mantissa to be scrutinised
* @return The digits only
*/
private static String retrieveDigits(final char separator, String number) {
// Strip off exponent part, if it exists:
short eAt = (short)number.indexOf(EXPONENT);
if (eAt > -1) {
number = number.substring(0, eAt);
}
return number.replace((new Character(StringUtils.DASH)).toString(), "").
replace((new Character(separator)).toString(), "");
}
// ---- Public methods ----------------------
/**
* Returns the number of digits in the long value.
*
* @param value the value
* @return the byte
*/
public static byte digits(final long value) {
return (byte) StringUtils.filter(Long.toString(value), ".,").length();
}
/**
* Finds the significant digits after the decimal separator of a mantissa.
*
* @param separator Language-specific decimal separator
* @param number Value to be scrutinised
* @return Number of significant zeros after decimal separator.
*/
public static byte findSignificantsAfterDecimal(final char separator,
final double number) {
if (number == 0) { return 1; }
else {
String value = (new Double(number)).toString();
final short separatorAt = (short) value.indexOf(separator);
if (separatorAt > -1) {
value = value.substring(separatorAt + 1);
}
final short exponentAt = (short) value.indexOf(EXPONENT);
if (exponentAt > 0) {
value = value.substring(0, exponentAt);
}
final Long longValue = new Long(value).longValue();
if (Math.abs(number) < 1) {
return (byte) longValue.toString().length();
} else if (longValue == 0) {
return 0;
} else {
return (byte) (("0." + value).length() - 2);
}
}
}
/**
* Calculates the power of the base to the exponent without changing the
* least-significant digits of a number.
*
* @param basis
* @param exponent
* @return basis to power of exponent
*/
public static double power(final int basis, final short exponent) {
return power((short) basis, exponent);
}
/**
* Calculates the power of the base to the exponent without changing the
* least-significant digits of a number.
*
* @param basis the basis
* @param exponent the exponent
* @return basis to power of exponent
*/
public static double power(final short basis, final short exponent) {
if (basis == 0) {
return (exponent != 0) ? 1 : 0;
} else {
if (exponent == 0) {
return 1;
} else {
// The Math method power does change the least significant
// digits after the decimal separator and is therefore useless.
double result = 1;
short s = 0;
if (exponent > 0) {
for (; s < exponent; s++) {
result *= basis;
}
} else if (exponent < 0) {
for (s = exponent; s < 0; s++) {
result /= basis;
}
}
return result;
}
}
}
/**
* Rounds a number to the decimal places.
*
* @param significantsAfter Requested significant digits after decimal
* @param separator Language-specific decimal separator
* @param number Number to be rounded
* @return Rounded number to the requested decimal places
*/
public static double round(final byte significantsAfter,
final char separator,
final double number) {
if (number == 0) { return 0; }
else {
final double constant = power(10, (short)
(findInsignificantZerosAfterDecimal(separator, number)
+ significantsAfter));
final short dExponent = findExponent(number);
short exponent = dExponent;
double value = number*constant*Math.pow(10, -exponent);
final String exponentSign =
(exponent < 0) ? String.valueOf(StringUtils.DASH) : "";
if (exponent != 0) {
exponent = (short) Math.abs(exponent);
value = round(value);
} else {
value = round(value)/constant;
}
// Power method cannot be used, as the exponentiated number may
// exceed the maximal long value.
exponent -= Math.signum(dExponent)*(findSignificantDigits
(significantsAfter, separator, value) - 1);
if (dExponent != 0) {
String strValue = Double.toString(value);
strValue = strValue.substring(0, strValue.indexOf(separator))
+ EXPONENT + exponentSign + Short.toString(exponent);
value = new Double(strValue);
}
return value;
}
}
/**
* Rounds a number according to mathematical rules.
*
* @param value the value
* @return the double
*/
public static double round(final double value) {
return (long) (value + .5);
}
/**
* Rounds to a fixed number of significant digits.
*
* @param significantDigits Requested number of significant digits
* @param separator Language-specific decimal separator
* @param dNumber Number to be rounded
* @return Rounded number
*/
public static String roundToString(final byte significantDigits,
final char separator,
double dNumber) {
// Number of significants that *are* before the decimal separator:
final byte significantsBefore =
findSignificantsBeforeDecimal(separator, dNumber);
// Number of decimals that *should* be after the decimal separator:
final byte significantsAfter = findSignificantsAfterDecimal(
significantsBefore, significantDigits);
// Round to the specified number of digits after decimal separator:
final double rounded = MathsUtils.round(significantsAfter, separator, dNumber);
final String exponent = findExponent((new Double(rounded)).toString());
final String mantissa = findMantissa(separator,
(new Double(rounded)).toString());
final double dMantissa = new Double(mantissa).doubleValue();
final StringBuilder result = new StringBuilder(mantissa);
// Determine the significant digits in this number:
final byte significants = findSignificantDigits(significantsAfter,
separator, dMantissa);
// Add lagging zeros, if necessary:
if (significants <= significantDigits) {
if (significantsAfter != 0) {
result.append(ZEROS.substring(0,
calculateMissingSignificantZeros(significantsAfter,
separator, dMantissa)));
} else {
// Cut off the decimal separator & after decimal digits:
final short decimal = (short) result.indexOf(
new Character(separator).toString());
if (decimal > -1) {
result.setLength(decimal);
}
}
} else if (significantsBefore > significantDigits) {
dNumber /= power(10, (short) (significantsBefore - significantDigits));
dNumber = round(dNumber);
final short digits =
(short) (significantDigits + ((dNumber < 0) ? 1 : 0));
final String strDouble = (new Double(dNumber)).toString().substring(0, digits);
result.setLength(0);
result.append(strDouble + ZEROS.substring(0,
significantsBefore - significantDigits));
}
if (new Short(exponent) != 0) {
result.append(EXPONENT + exponent);
}
return result.toString();
} // public static String roundToString(…)
/**
* Rounds to a fixed number of significant digits.
*
* @param separator Language-specific decimal separator
* @param significantDigits Requested number of significant digits
* @param value Number to be rounded
* @return Rounded number
*/
public static String roundToString(final char separator,
final int significantDigits,
float value) {
return roundToString((byte)significantDigits, separator,
(double)value);
}
} // class MathsUtils
|
The code is tested with the following JUnit test:
Code listing 3.22: MathsUtilsTest.java
package string;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Vector;
import org.junit.Test;
/**
* The JUnit test for the <code>MathsUtils</code> class.
*
* @since 2013-03-26
* @version 2014-10-14
*/
public class MathsUtilsTest {
/**
* Method that adds a negative and a positive value to values.
*
* @param d the double value
* @param values the values
*/
private static void addValue(final double d, Vector<Double> values) {
values.add(-d);
values.add(d);
}
// Public methods ------
/**
* Tests the round method with a double parameter.
*/
@Test
public void testRoundToStringDoubleByteCharDouble() {
// Test rounding
final Vector<Double> values = new Vector<Double>();
final Vector<String> strValues = new Vector<String>();
values.add(0.0);
strValues.add("0.00000");
addValue(1.4012984643248202e-45, values);
strValues.add("-1.4012E-45");
strValues.add("1.4013E-45");
addValue(1.999999757e-5, values);
strValues.add("-1.9999E-5");
strValues.add("2.0000E-5");
addValue(1.999999757e-4, values);
strValues.add("-1.9999E-4");
strValues.add("2.0000E-4");
addValue(1.999999757e-3, values);
strValues.add("-0.0019999");
strValues.add("0.0020000");
addValue(0.000640589, values);
strValues.add("-6.4058E-4");
strValues.add("6.4059E-4");
addValue(0.3396899998188019, values);
strValues.add("-0.33968");
strValues.add("0.33969");
addValue(0.34, values);
strValues.add("-0.33999");
strValues.add("0.34000");
addValue(7.07, values);
strValues.add("-7.0699");
strValues.add("7.0700");
addValue(118.188, values);
strValues.add("-118.18");
strValues.add("118.19");
addValue(118.2, values);
strValues.add("-118.19");
strValues.add("118.20");
addValue(123.405009, values);
strValues.add("-123.40");
strValues.add("123.41");
addValue(30.76994323730469, values);
strValues.add("-30.769");
strValues.add("30.770");
addValue(130.76994323730469, values);
strValues.add("-130.76");
strValues.add("130.77");
addValue(540, values);
strValues.add("-539.99");
strValues.add("540.00");
addValue(12345, values);
strValues.add("-12344");
strValues.add("12345");
addValue(123456, values);
strValues.add("-123450");
strValues.add("123460");
addValue(540911, values);
strValues.add("-540900");
strValues.add("540910");
addValue(9.223372036854776e56, values);
strValues.add("-9.2233E56");
strValues.add("9.2234E56");
byte i = 0;
final byte significants = 5;
for (final double element : values) {
final String strValue;
try {
strValue = MathsUtils.roundToString(significants, StringUtils.PERIOD, element);
System.out.println(" MathsUtils.round(" + significants + ", '"
+ StringUtils.PERIOD + "', " + element + ") ==> "
+ strValue + " = " + strValues.get(i));
assertEquals("Testing roundToString", strValue, strValues.get(i++));
} catch (final Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} // class MathsUtilsTest
|
The output of the JUnit test follows:
Output for code listing 3.22
MathsUtils.round(5, '.', 0.0) ==> 0.00000 = 0.00000 MathsUtils.round(5, '.', -1.4012984643248202E-45) ==> -1.4012E-45 = -1.4012E-45 MathsUtils.round(5, '.', 1.4012984643248202E-45) ==> 1.4013E-45 = 1.4013E-45 MathsUtils.round(5, '.', -1.999999757E-5) ==> -1.9999E-5 = -1.9999E-5 MathsUtils.round(5, '.', 1.999999757E-5) ==> 2.0000E-5 = 2.0000E-5 MathsUtils.round(5, '.', -1.999999757E-4) ==> -1.9999E-4 = -1.9999E-4 MathsUtils.round(5, '.', 1.999999757E-4) ==> 2.0000E-4 = 2.0000E-4 MathsUtils.round(5, '.', -0.001999999757) ==> -0.0019999 = -0.0019999 MathsUtils.round(5, '.', 0.001999999757) ==> 0.0020000 = 0.0020000 MathsUtils.round(5, '.', -6.40589E-4) ==> -6.4058E-4 = -6.4058E-4 MathsUtils.round(5, '.', 6.40589E-4) ==> 6.4059E-4 = 6.4059E-4 MathsUtils.round(5, '.', -0.3396899998188019) ==> -0.33968 = -0.33968 MathsUtils.round(5, '.', 0.3396899998188019) ==> 0.33969 = 0.33969 MathsUtils.round(5, '.', -0.34) ==> -0.33999 = -0.33999 MathsUtils.round(5, '.', 0.34) ==> 0.34000 = 0.34000 MathsUtils.round(5, '.', -7.07) ==> -7.0699 = -7.0699 MathsUtils.round(5, '.', 7.07) ==> 7.0700 = 7.0700 MathsUtils.round(5, '.', -118.188) ==> -118.18 = -118.18 MathsUtils.round(5, '.', 118.188) ==> 118.19 = 118.19 MathsUtils.round(5, '.', -118.2) ==> -118.19 = -118.19 MathsUtils.round(5, '.', 118.2) ==> 118.20 = 118.20 MathsUtils.round(5, '.', -123.405009) ==> -123.40 = -123.40 MathsUtils.round(5, '.', 123.405009) ==> 123.41 = 123.41 MathsUtils.round(5, '.', -30.76994323730469) ==> -30.769 = -30.769 MathsUtils.round(5, '.', 30.76994323730469) ==> 30.770 = 30.770 MathsUtils.round(5, '.', -130.7699432373047) ==> -130.76 = -130.76 MathsUtils.round(5, '.', 130.7699432373047) ==> 130.77 = 130.77 MathsUtils.round(5, '.', -540.0) ==> -539.99 = -539.99 MathsUtils.round(5, '.', 540.0) ==> 540.00 = 540.00 MathsUtils.round(5, '.', -12345.0) ==> -12344 = -12344 MathsUtils.round(5, '.', 12345.0) ==> 12345 = 12345 MathsUtils.round(5, '.', -123456.0) ==> -123450 = -123450 MathsUtils.round(5, '.', 123456.0) ==> 123460 = 123460 MathsUtils.round(5, '.', -540911.0) ==> -540900 = -540900 MathsUtils.round(5, '.', 540911.0) ==> 540910 = 540910 MathsUtils.round(5, '.', -9.223372036854776E56) ==> -9.2233E56 = -9.2233E56 MathsUtils.round(5, '.', 9.223372036854776E56) ==> 9.2234E56 = 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.