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 constantsEdit

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

Math.EEdit

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.PIEdit

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;
    

Math methodsEdit

Exponential methodsEdit

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

ExponentiationEdit

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).

LogarithmsEdit

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 methodsEdit

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 functionsEdit

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 functionsEdit

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

Hyperbolic functionsEdit

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

Radian/degree conversionEdit

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.absEdit

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 valuesEdit

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.

Functions dealing with floating-point representationEdit

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.

Rounding number exampleEdit

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.  
    
  14. 	/**
    
  15. 	 * Removes all occurrences of the filter character in the text.
    
  16. 	 *
    
  17. 	 * @param text Text to be filtered
    
  18. 	 * @param filter The character to be removed.
    
  19. 	 * @return the string
    
  20. 	 */
    
  21. 	public static String filter(final String text, final String filter) {
    
  22. 		final String[] words = text.split("[" + filter + "]");
    
  23.  
    
  24. 		switch (words.length) {
    
  25. 		case 0:
    
  26. 			return text;
    
  27. 		case 1:
    
  28. 			return words[0];
    
  29. 		default:
    
  30. 			final StringBuilder filteredText = new StringBuilder();
    
  31.  
    
  32. 			for (final String word : words) {
    
  33. 				filteredText.append(word);
    
  34. 			}
    
  35.  
    
  36. 			return filteredText.toString();
    
  37. 		}
    
  38. 	}
    
  39. }
    

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.<br/>
    
  5.  * ATTENTION:<br/>Should depend only on standard Java libraries!
    
  6.  *
    
  7.  * @version 2013-09-05
    
  8.  */
    
  9. public class Maths {
    
  10.  
    
  11. 	// CONSTANTS
    
  12. 	// ------------------------------------------
    
  13.  
    
  14. 	/** The exponent sign in a scientific number, or the capital letter E. */
    
  15. 	public static final char EXPONENT = 'E';
    
  16.  
    
  17. 	/** Value after which the language switches from scientific to double */
    
  18. 	private static final double E_TO_DOUBLE = 1E-3;
    
  19.  
    
  20. 	/** The zero string constant used at several places. */
    
  21. 	public static final String ZERO = "0";
    
  22.  
    
  23. 	/** The string of zeros */
    
  24. 	private static final String ZEROS = "000000000000000000000000000000000";
    
  25.  
    
  26. 	// METHODS
    
  27. 	// ------------------------------------------
    
  28.  
    
  29. 	/**
    
  30. 	 * Determines, if the number uses a scientific representation.
    
  31. 	 *
    
  32. 	 * @param number the number
    
  33. 	 * @return true, if it is a scientific number, false otherwise
    
  34. 	 */
    
  35. 	private static boolean isScientific(final double number) {
    
  36. 		return ((new Double(number)).toString().indexOf(EXPONENT) > 0);
    
  37. 	}
    
  38.  
    
  39. 	/**
    
  40. 	 * Determines how many zeros are to be appended after the decimal digits.
    
  41. 	 *
    
  42. 	 * @param significantsAfter Requested significant digits after decimal
    
  43. 	 * @param separator Language-specific decimal separator
    
  44. 	 * @param number Rounded number
    
  45. 	 * @return Requested value
    
  46. 	 */
    
  47. 	private static byte calculateMissingSignificantZeros(
    
  48. 			final byte significantsAfter,
    
  49. 			final char separator,
    
  50. 			final double number) {
    
  51.  
    
  52. 		final byte after = findSignificantsAfterDecimal(separator, number);
    
  53.  
    
  54. 		final byte zeros =
    
  55. 				(byte) (significantsAfter - ((after == 0) ? 1 : after));
    
  56.  
    
  57. 		return ((zeros >= 0) ? zeros : 0);
    
  58. 	}
    
  59.  
    
  60. 	/**
    
  61. 	 * Finds the insignificant zeros after the decimal separator.
    
  62. 	 *
    
  63. 	 * @param separator Language-specific decimal separator
    
  64. 	 * @param number the number
    
  65. 	 * @return the byte
    
  66. 	 */
    
  67. 	private static byte findInsignificantZerosAfterDecimal(
    
  68. 			final char separator,
    
  69. 			final double number) {
    
  70.  
    
  71. 		if ((Math.abs(number) >= 1) || isScientific(number)) {
    
  72. 			return 0;
    
  73. 		} else {
    
  74. 			final StringBuilder string = new StringBuilder();
    
  75.  
    
  76. 			string.append(number);
    
  77. 			string.delete(0,
    
  78. 					string.indexOf(new Character(separator).toString()) + 1);
    
  79.  
    
  80. 			// Determine what to match:
    
  81. 			final String regularExpression = "[1-9]";
    
  82.  
    
  83. 			final String[] split = string.toString().split(regularExpression);
    
  84.  
    
  85. 			return (split.length > 0) ? (byte) split[0].length() : 0;
    
  86. 		}
    
  87. 	}
    
  88.  
    
  89. 	/**
    
  90. 	 * Calculates the number of all significant digits (without the sign and
    
  91. 	 * the decimal separator).
    
  92. 	 *
    
  93. 	 * @param significantsAfter Requested significant digits after decimal
    
  94. 	 * @param separator Language-specific decimal separator
    
  95. 	 * @param number Value where the digits are to be counted
    
  96. 	 * @return Number of significant digits
    
  97. 	 */
    
  98. 	private static byte findSignificantDigits(final byte significantsAfter,
    
  99. 			final char separator,
    
  100. 			final double number) {
    
  101.  
    
  102. 		if (number == 0) return 0;
    
  103. 		else {
    
  104. 			String mantissa =
    
  105. 					findMantissa(separator, new Double(number).toString());
    
  106.  
    
  107. 			if (number == (long)number) {
    
  108. 				mantissa = mantissa.substring(0, mantissa.length() - 1);
    
  109. 			}
    
  110.  
    
  111. 			mantissa = retrieveDigits(separator, mantissa);
    
  112. 			// Find the position of the first non-zero digit:
    
  113. 			short nonZeroAt = 0;
    
  114.  
    
  115. 			for (; (nonZeroAt < mantissa.length())
    
  116. 					&& (mantissa.charAt(nonZeroAt) == '0'); nonZeroAt++) ;
    
  117.  
    
  118. 			return (byte)mantissa.substring(nonZeroAt).length();
    
  119. 		}
    
  120. 	}
    
  121.  
    
  122. 	/**
    
  123. 	 * Determines the number of significant digits after the decimal separator
    
  124. 	 * knowing the total number of significant digits and the number before the
    
  125. 	 * decimal separator.
    
  126. 	 *
    
  127. 	 * @param significantsBefore Number of significant digits before separator
    
  128. 	 * @param significantDigits Number of all significant digits
    
  129. 	 * @return Number of significant decimals after the separator
    
  130. 	 */
    
  131. 	private static byte findSignificantsAfterDecimal(
    
  132. 			final byte significantsBefore,
    
  133. 			final byte significantDigits) {
    
  134.  
    
  135. 		final byte afterDecimal =
    
  136. 				(byte) (significantDigits - significantsBefore);
    
  137.  
    
  138. 		return (byte) ((afterDecimal > 0) ? afterDecimal : 0);
    
  139. 	}
    
  140.  
    
  141. 	/**
    
  142. 	 * Determines the number of digits before the decimal point.
    
  143. 	 *
    
  144. 	 * @param separator Language-specific decimal separator
    
  145. 	 * @param number Value to be scrutinised
    
  146. 	 * @return Number of digits before the decimal separator
    
  147. 	 */
    
  148. 	private static byte findSignificantsBeforeDecimal(final char separator,
    
  149. 			final double number) {
    
  150.  
    
  151. 		final String value = new Double(number).toString();
    
  152.  
    
  153. 		// Return immediately, if result is clear: Special handling at
    
  154. 		// crossroads of floating point and exponential numbers:
    
  155. 		if ((number == 0) || (Math.abs(number) >= E_TO_DOUBLE)
    
  156. 				&& (Math.abs(number) < 1)) {
    
  157.  
    
  158. 			return 0;
    
  159. 		} else if ((Math.abs(number) > 0) && (Math.abs(number) < E_TO_DOUBLE)) {
    
  160. 			return 1;
    
  161. 		} else {
    
  162. 			byte significants = 0;
    
  163. 			// Significant digits to the right of decimal separator:
    
  164. 			for (byte b = 0; b < value.length(); b++) {
    
  165. 				if (value.charAt(b) == separator) {
    
  166. 					break;
    
  167. 				} else if (value.charAt(b) != Common.DASH) {
    
  168. 					significants++;
    
  169. 				}
    
  170. 			}
    
  171.  
    
  172. 			return significants;
    
  173. 		}
    
  174. 	}
    
  175.  
    
  176. 	/**
    
  177. 	 * Returns the exponent part of the double number.
    
  178. 	 *
    
  179. 	 * @param number Value of which the exponent is of interest
    
  180. 	 * @return Exponent of the number or zero.
    
  181. 	 */
    
  182. 	private static short findExponent(final double number) {
    
  183. 		return new Short(findExponent((new Double(number)).toString()));
    
  184. 	}
    
  185.  
    
  186. 	/**
    
  187. 	 * Finds the exponent of a number.
    
  188. 	 *
    
  189. 	 * @param value Value where an exponent is to be searched
    
  190. 	 * @return Exponent, if it exists, or "0".
    
  191. 	 */
    
  192. 	private static String findExponent(final String value) {
    
  193. 		final short exponentAt = (short) value.indexOf(EXPONENT);
    
  194.  
    
  195. 		if (exponentAt < 0) {
    
  196. 			return ZERO;
    
  197. 		} else {
    
  198. 			return value.substring(exponentAt + 1);
    
  199. 		}
    
  200. 	}
    
  201.  
    
  202. 	/**
    
  203. 	 * Finds the mantissa of a number.
    
  204. 	 *
    
  205. 	 * @param separator Language-specific decimal separator
    
  206. 	 * @param value Value where the mantissa is to be found
    
  207. 	 * @return Mantissa of the number
    
  208. 	 */
    
  209. 	private static String findMantissa(final char separator,
    
  210. 			final String value) {
    
  211.  
    
  212. 		String strValue = value;
    
  213.  
    
  214. 		final short exponentAt = (short) strValue.indexOf(EXPONENT);
    
  215.  
    
  216. 		if (exponentAt > -1) {
    
  217. 			strValue = strValue.substring(0, exponentAt);
    
  218. 		}
    
  219.  
    
  220. 		return strValue;
    
  221. 	}
    
  222.  
    
  223. 	/**
    
  224. 	 * Retrieves the digits of the value without decimal separator or sign.
    
  225. 	 *
    
  226. 	 * @param separator
    
  227. 	 * @param number Mantissa to be scrutinised
    
  228. 	 * @return The digits only
    
  229. 	 */
    
  230. 	private static String retrieveDigits(final char separator, String number) {
    
  231. 		// Strip off exponent part, if it exists:
    
  232. 		short eAt = (short)number.indexOf(EXPONENT);
    
  233.  
    
  234. 		if (eAt > -1) {
    
  235. 			number = number.substring(0, eAt);
    
  236. 		}
    
  237.  
    
  238. 		return number.replace((new Character(Common.DASH)).toString(), "").
    
  239. 				replace((new Character(separator)).toString(), "");
    
  240. 	}
    
  241.  
    
  242.  
    
  243. 	// ---- Public methods ----------------------
    
  244.  
    
  245. 	/**
    
  246. 	 * Returns the number of digits in the long value.
    
  247. 	 *
    
  248. 	 * @param value the value
    
  249. 	 * @return the byte
    
  250. 	 */
    
  251. 	public static byte digits(final long value) {
    
  252. 		return (byte) Common.filter(Long.toString(value), ".,").length();
    
  253. 	}
    
  254.  
    
  255. 	/**
    
  256. 	 * Finds the significant digits after the decimal separator of a mantissa.
    
  257. 	 *
    
  258. 	 * @param separator Language-specific decimal separator
    
  259. 	 * @param number Value to be scrutinised
    
  260. 	 * @return Number of significant zeros after decimal separator.
    
  261. 	 */
    
  262. 	public static byte findSignificantsAfterDecimal(final char separator,
    
  263. 			final double number) {
    
  264.  
    
  265. 		if (number == 0) {
    
  266. 			return 1;
    
  267. 		} else {
    
  268. 			String value = (new Double(number)).toString();
    
  269.  
    
  270. 			final short separatorAt = (short) value.indexOf(separator);
    
  271.  
    
  272. 			if (separatorAt > -1) {
    
  273. 				value = value.substring(separatorAt + 1);
    
  274. 			}
    
  275.  
    
  276. 			final short exponentAt = (short) value.indexOf(EXPONENT);
    
  277.  
    
  278. 			if (exponentAt > 0) {
    
  279. 				value = value.substring(0, exponentAt);
    
  280. 			}
    
  281.  
    
  282. 			final Long longValue = new Long(value).longValue();
    
  283.  
    
  284. 			if (Math.abs(number) < 1) {
    
  285. 				return (byte) longValue.toString().length();
    
  286. 			} else if (longValue == 0) {
    
  287. 				return 0;
    
  288. 			} else {
    
  289. 				return (byte) (("0." + value).length() - 2);
    
  290. 			}
    
  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. 	 *
    
  298. 	 * @param basis
    
  299. 	 * @param exponent
    
  300. 	 * @return basis to power of exponent
    
  301. 	 */
    
  302. 	public static double power(final int basis, final short exponent) {
    
  303. 		return power((short) basis, exponent);
    
  304. 	}
    
  305.  
    
  306. 	/**
    
  307. 	 * Calculates the power of the base to the exponent without changing the
    
  308. 	 * least-significant digits of a number.
    
  309. 	 *
    
  310. 	 * @param basis the basis
    
  311. 	 * @param exponent the exponent
    
  312. 	 * @return basis to power of exponent
    
  313. 	 */
    
  314. 	public static double power(final short basis, final short exponent) {
    
  315. 		if (basis == 0) {
    
  316. 			return (exponent != 0) ? 1 : 0;
    
  317. 		} else {
    
  318. 			if (exponent == 0) {
    
  319. 				return 1;
    
  320. 			} else {
    
  321. 				// The Math method power does change the least significant
    
  322. 				// digits after the decimal separator and is therefore useless.
    
  323. 				double result = 1;
    
  324. 				short s = 0;
    
  325.  
    
  326. 				if (exponent > 0) {
    
  327. 					for (; s < exponent; s++) {
    
  328. 						result *= basis;
    
  329. 					}
    
  330. 				} else if (exponent < 0) {
    
  331. 					for (s = exponent; s < 0; s++) {
    
  332. 						result /= basis;
    
  333. 					}
    
  334. 				}
    
  335.  
    
  336. 				return result;
    
  337. 			}
    
  338. 		}
    
  339. 	}
    
  340.  
    
  341. 	/**
    
  342. 	 * Rounds a number to the decimal places.
    
  343. 	 *
    
  344. 	 * @param significantsAfter Requested significant digits after decimal
    
  345. 	 * @param separator Language-specific decimal separator
    
  346. 	 * @param number Number to be rounded
    
  347. 	 * @return Rounded number to the requested decimal places
    
  348. 	 */
    
  349. 	public static double round(final byte significantsAfter,
    
  350. 			final char separator,
    
  351. 			final double number) {
    
  352.  
    
  353. 		if (number == 0) {
    
  354. 			return 0;
    
  355. 		} else {
    
  356. 			final double constant = power(10, (short)
    
  357. 					(findInsignificantZerosAfterDecimal(separator, number)
    
  358. 							+ significantsAfter));
    
  359. 			final short dExponent = findExponent(number);
    
  360.  
    
  361. 			short exponent = dExponent;
    
  362.  
    
  363. 			double value = number*constant*Math.pow(10, -exponent);
    
  364. 			final String exponentSign =
    
  365. 					(exponent < 0) ? String.valueOf(Common.DASH) : "";
    
  366.  
    
  367. 			if (exponent != 0) {
    
  368. 				exponent = (short) Math.abs(exponent);
    
  369.  
    
  370. 				value = round(value);
    
  371. 			} else {
    
  372. 				value = round(value)/constant;
    
  373. 			}
    
  374.  
    
  375. 			// Power method cannot be used, as the exponentiated number may
    
  376. 			// exceed the maximal long value.
    
  377. 			exponent -= Math.signum(dExponent)*(findSignificantDigits
    
  378. 					(significantsAfter, separator, value) - 1);
    
  379.  
    
  380. 			if (dExponent != 0) {
    
  381. 				String strValue = Double.toString(value);
    
  382.  
    
  383. 				strValue = strValue.substring(0, strValue.indexOf(separator))
    
  384. 						+ EXPONENT + exponentSign + Short.toString(exponent);
    
  385.  
    
  386. 				value = new Double(strValue);
    
  387. 			}
    
  388.  
    
  389. 			return value;
    
  390. 		}
    
  391. 	}
    
  392.  
    
  393. 	/**
    
  394. 	 * Rounds a number according to mathematical rules.
    
  395. 	 *
    
  396. 	 * @param value the value
    
  397. 	 * @return the double
    
  398. 	 */
    
  399. 	public static double round(final double value) {
    
  400. 		return (long) (value + .5);
    
  401. 	}
    
  402.  
    
  403. 	/**
    
  404. 	 * Rounds to a fixed number of significant digits.
    
  405. 	 *
    
  406. 	 * @param significantDigits Requested number of significant digits
    
  407. 	 * @param separator Language-specific decimal separator
    
  408. 	 * @param dNumber Number to be rounded
    
  409. 	 * @return Rounded number
    
  410. 	 */
    
  411. 	public static String roundToString(final byte significantDigits,
    
  412. 			final char separator,
    
  413. 			double dNumber) {
    
  414. 		// Number of significants that *are* before the decimal separator:
    
  415. 		final byte significantsBefore =
    
  416. 			findSignificantsBeforeDecimal(separator, dNumber);
    
  417. 		// Number of decimals that *should* be after the decimal separator:
    
  418. 		final byte significantsAfter = findSignificantsAfterDecimal(
    
  419. 				significantsBefore, significantDigits);
    
  420. 		// Round to the specified number of digits after decimal separator:
    
  421. 		final double rounded = Maths.round(significantsAfter, separator, dNumber);
    
  422.  
    
  423. 		final String exponent = findExponent((new Double(rounded)).toString());
    
  424. 		final String mantissa = findMantissa(separator,
    
  425. 						(new Double(rounded)).toString());
    
  426.  
    
  427. 		final double dMantissa = new Double(mantissa).doubleValue();
    
  428. 		final StringBuilder result = new StringBuilder(mantissa);
    
  429. 		// Determine the significant digits in this number:
    
  430. 		final byte significants = findSignificantDigits(significantsAfter,
    
  431. 				separator, dMantissa);
    
  432. 		// Add lagging zeros, if necessary:
    
  433. 		if (significants <= significantDigits) {
    
  434. 			if (significantsAfter != 0) {
    
  435. 				result.append(ZEROS.substring(0,
    
  436. 						calculateMissingSignificantZeros(significantsAfter,
    
  437. 								separator, dMantissa)));
    
  438. 			} else {
    
  439. 				// Cut off the decimal separator & after decimal digits:
    
  440. 				final short decimal = (short) result.indexOf(
    
  441. 						new Character(separator).toString());
    
  442.  
    
  443. 				if (decimal > -1) {
    
  444. 					result.setLength(decimal);
    
  445. 				}
    
  446. 			}
    
  447. 		} else if (significantsBefore > significantDigits) {
    
  448. 			dNumber /= power(10, (short) (significantsBefore - significantDigits));
    
  449.  
    
  450. 			dNumber = round(dNumber);
    
  451.  
    
  452. 			final short digits =
    
  453. 					(short) (significantDigits + ((dNumber < 0) ? 1 : 0));
    
  454.  
    
  455. 			final String strDouble = (new Double(dNumber)).toString().substring(0, digits);
    
  456.  
    
  457. 			result.setLength(0);
    
  458. 			result.append(strDouble + ZEROS.substring(0,
    
  459. 					significantsBefore - significantDigits));
    
  460. 		}
    
  461.  
    
  462. 		if (new Short(exponent) != 0) {
    
  463. 			result.append(EXPONENT + exponent);
    
  464. 		}
    
  465.  
    
  466. 		return result.toString();
    
  467. 	} // public static String roundToString(…)
    
  468.  
    
  469. 	/**
    
  470. 	 * Rounds to a fixed number of significant digits.
    
  471. 	 *
    
  472. 	 * @param separator Language-specific decimal separator
    
  473. 	 * @param significantDigits Requested number of significant digits
    
  474. 	 * @param value Number to be rounded
    
  475. 	 * @return Rounded number
    
  476. 	 */
    
  477. 	public static String roundToString(final char separator,
    
  478. 			final int significantDigits,
    
  479. 			float value) {
    
  480.  
    
  481. 		return roundToString((byte)significantDigits, separator,
    
  482. 				(double)value);
    
  483. 	}
    
  484. } // class Maths
    

The code is tested with the following JUnit test:

Computer code Code listing 3.22: MathsTest.java
  1. package common;
    
  2.  
    
  3. import static org.junit.Assert.assertEquals;
    
  4. import static org.junit.Assert.assertFalse;
    
  5. import static org.junit.Assert.assertTrue;
    
  6.  
    
  7. import java.util.Vector;
    
  8.  
    
  9. import org.junit.Test;
    
  10.  
    
  11. /**
    
  12.  * The JUnit test for the <code>Maths</code> class.
    
  13.  *
    
  14.  * @since 2013-03-26
    
  15.  * @version 2013-09-05
    
  16.  */
    
  17. public class MathsTest {
    
  18.  
    
  19. 	/**
    
  20. 	 * Method that adds a negative and a positive value to values.
    
  21. 	 *
    
  22. 	 * @param d the double value
    
  23. 	 * @param values the values
    
  24. 	 */
    
  25. 	private static void addValue(final double d, Vector<Double> values) {
    
  26. 		values.add(-d);
    
  27. 		values.add(d);
    
  28. 	}
    
  29.  
    
  30. 	// Public methods ------
    
  31.  
    
  32. 	/**
    
  33. 	 * Tests the round method with a double parameter.
    
  34. 	 */
    
  35. 	@Test
    
  36. 	public void testRoundToStringDoubleByteCharDouble() {
    
  37. 		// Test rounding
    
  38. 		final Vector<Double> values = new Vector<Double>();
    
  39. 		final Vector<String> strValues = new Vector<String>();
    
  40.  
    
  41. 		values.add(0.0);
    
  42. 		strValues.add("0.00000");
    
  43. 		addValue(1.4012984643248202e-45, values);
    
  44. 		strValues.add("-1.4012E-45");
    
  45. 		strValues.add("1.4013E-45");
    
  46. 		addValue(1.999999757e-5, values);
    
  47. 		strValues.add("-1.9999E-5");
    
  48. 		strValues.add("2.0000E-5");
    
  49. 		addValue(1.999999757e-4, values);
    
  50. 		strValues.add("-1.9999E-4");
    
  51. 		strValues.add("2.0000E-4");
    
  52. 		addValue(1.999999757e-3, values);
    
  53. 		strValues.add("-0.0019999");
    
  54. 		strValues.add("0.0020000");
    
  55. 		addValue(0.000640589, values);
    
  56. 		strValues.add("-6.4058E-4");
    
  57. 		strValues.add("6.4059E-4");
    
  58. 		addValue(0.3396899998188019, values);
    
  59. 		strValues.add("-0.33968");
    
  60. 		strValues.add("0.33969");
    
  61. 		addValue(0.34, values);
    
  62. 		strValues.add("-0.33999");
    
  63. 		strValues.add("0.34000");
    
  64. 		addValue(7.07, values);
    
  65. 		strValues.add("-7.0699");
    
  66. 		strValues.add("7.0700");
    
  67. 		addValue(118.188, values);
    
  68. 		strValues.add("-118.18");
    
  69. 		strValues.add("118.19");
    
  70. 		addValue(118.2, values);
    
  71. 		strValues.add("-118.19");
    
  72. 		strValues.add("118.20");
    
  73. 		addValue(123.405009, values);
    
  74. 		strValues.add("-123.40");
    
  75. 		strValues.add("123.41");
    
  76. 		addValue(30.76994323730469, values);
    
  77. 		strValues.add("-30.769");
    
  78. 		strValues.add("30.770");
    
  79. 		addValue(130.76994323730469, values);
    
  80. 		strValues.add("-130.76");
    
  81. 		strValues.add("130.77");
    
  82. 		addValue(540, values);
    
  83. 		strValues.add("-539.99");
    
  84. 		strValues.add("540.00");
    
  85. 		addValue(12345, values);
    
  86. 		strValues.add("-12344");
    
  87. 		strValues.add("12345");
    
  88. 		addValue(123456, values);
    
  89. 		strValues.add("-123450");
    
  90. 		strValues.add("123460");
    
  91. 		addValue(540911, values);
    
  92. 		strValues.add("-540900");
    
  93. 		strValues.add("540910");
    
  94. 		addValue(9.223372036854776e56, values);
    
  95. 		strValues.add("-9.2233E56");
    
  96. 		strValues.add("9.2234E56");
    
  97.  
    
  98. 		byte i = 0;
    
  99. 		final byte significants = 5;
    
  100.  
    
  101. 		for (final double element : values) {
    
  102. 			final String strValue;
    
  103.  
    
  104. 			try {
    
  105. 				strValue = Maths.roundToString(significants, Common.PERIOD, element);
    
  106.  
    
  107. 				System.out.println(" Maths.round(" + significants  + ", '"
    
  108. 						+ Common.PERIOD + "', " + element + ") ==> "
    
  109. 						+ strValue + " = " + strValues.get(i));
    
  110. 				assertEquals("Testing roundToString", strValue, strValues.get(i++));
    
  111. 			} catch (final Exception e) {
    
  112. 				// TODO Auto-generated catch block
    
  113. 				e.printStackTrace();
    
  114. 			}
    
  115. 		}
    
  116. 	}
    
  117.  
    
  118. }	// class MathsTest
    

The output of the JUnit test follows:

Computer code Output for code listing 3.22
 Maths.round(5, '.', 0.0) ==> 0.00000 = 0.00000
 Maths.round(5, '.', -1.4012984643248202E-45) ==> -1.4012E-45 = -1.4012E-45
 Maths.round(5, '.', 1.4012984643248202E-45) ==> 1.4013E-45 = 1.4013E-45
 Maths.round(5, '.', -1.999999757E-5) ==> -1.9999E-5 = -1.9999E-5
 Maths.round(5, '.', 1.999999757E-5) ==> 2.0000E-5 = 2.0000E-5
 Maths.round(5, '.', -1.999999757E-4) ==> -1.9999E-4 = -1.9999E-4
 Maths.round(5, '.', 1.999999757E-4) ==> 2.0000E-4 = 2.0000E-4
 Maths.round(5, '.', -0.001999999757) ==> -0.0019999 = -0.0019999
 Maths.round(5, '.', 0.001999999757) ==> 0.0020000 = 0.0020000
 Maths.round(5, '.', -6.40589E-4) ==> -6.4058E-4 = -6.4058E-4
 Maths.round(5, '.', 6.40589E-4) ==> 6.4059E-4 = 6.4059E-4
 Maths.round(5, '.', -0.3396899998188019) ==> -0.33968 = -0.33968
 Maths.round(5, '.', 0.3396899998188019) ==> 0.33969 = 0.33969
 Maths.round(5, '.', -0.34) ==> -0.33999 = -0.33999
 Maths.round(5, '.', 0.34) ==> 0.34000 = 0.34000
 Maths.round(5, '.', -7.07) ==> -7.0699 = -7.0699
 Maths.round(5, '.', 7.07) ==> 7.0700 = 7.0700
 Maths.round(5, '.', -118.188) ==> -118.18 = -118.18
 Maths.round(5, '.', 118.188) ==> 118.19 = 118.19
 Maths.round(5, '.', -118.2) ==> -118.19 = -118.19
 Maths.round(5, '.', 118.2) ==> 118.20 = 118.20
 Maths.round(5, '.', -123.405009) ==> -123.40 = -123.40
 Maths.round(5, '.', 123.405009) ==> 123.41 = 123.41
 Maths.round(5, '.', -30.76994323730469) ==> -30.769 = -30.769
 Maths.round(5, '.', 30.76994323730469) ==> 30.770 = 30.770
 Maths.round(5, '.', -130.7699432373047) ==> -130.76 = -130.76
 Maths.round(5, '.', 130.7699432373047) ==> 130.77 = 130.77
 Maths.round(5, '.', -540.0) ==> -539.99 = -539.99
 Maths.round(5, '.', 540.0) ==> 540.00 = 540.00
 Maths.round(5, '.', -12345.0) ==> -12344 = -12344
 Maths.round(5, '.', 12345.0) ==> 12345 = 12345
 Maths.round(5, '.', -123456.0) ==> -123450 = -123450
 Maths.round(5, '.', 123456.0) ==> 123460 = 123460
 Maths.round(5, '.', -540911.0) ==> -540900 = -540900
 Maths.round(5, '.', 540911.0) ==> 540910 = 540910
 Maths.round(5, '.', -9.223372036854776E56) ==> -9.2233E56 = -9.2233E56
 Maths.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.

Clipboard

To do:
Add some exercises like the ones in Variables

Arrays Java Programming
Mathematical functions
Large numbers
Last modified on 5 September 2013, at 14:57