Java high-precision big numeric operations

Source: Internet
Author: User
Tags mul

Java high-precision big numeric operations
In order to solve the problem of overflow and inaccuracy in Calculation of Java basic data types. Java provides two classes: BigInteger and BigDecimal, specifically used for high-precision operations. Anything that can be done with int or float can also be done with BigInteger and BigDecimal, but must be called using methods instead of operators.
High-precision Integer BigInteger
BigInteger supports Integers of any precision, that is, we can accurately represent integer values of any size. At the same time, no information is lost during the operation;
High-precision floating point BigDecimal

It can represent decimal places of any precision and calculate them. Since BigDecimal objects are unchangeable, each of these methods generates a new BigDecimal object. Therefore, because of the overhead of object creation, BigDecimal is not suitable for a large number of mathematical calculations, but it is designed to accurately represent decimals.

 

Import java. math. bigDecimal; import java. math. bigInteger; public class BigNumber {// default division operation precision, that is, the number of decimal places to be retained private static final int DEFAULT_DIV_SCALE = 10; // This class cannot be instantiated private BigNumber () {}/*** provides precise addition operations. * @ Param v1 add count * @ param v2 add count * @ return and */public static double add (double v1, double v2) {BigDecimal b1 = new BigDecimal (Double. toString (v1); BigDecimal b2 = new BigDecimal (Double. toString (v2); return (b1.add (b2 )). doubleValue ();}/*** provides precise subtraction. * @ Param v1 subtrahend * @ param v2 subtrahend * @ return Difference Between Two Parameters */public static double sub (double v1, double v2) {BigDecimal b1 = new BigDecimal (Double. toString (v1); BigDecimal b2 = new BigDecimal (Double. toString (v2); return (b1.subtract (b2 )). doubleValue ();}/*** provides exact multiplication. * @ Param v1 multiplier * @ param v2 multiplier * @ return product of two parameters */public static double mul (double v1, double v2) {BigDecimal b1 = new BigDecimal (Double. toString (v1); BigDecimal b2 = new BigDecimal (Double. toString (v2); return (b1.multiply (b2 )). doubleValue ();}/*** provides (relatively) Precise Division operations. In case of division, the number of digits after the decimal point is accurate to *, and the number after the decimal point is rounded down. * @ Param v1 divisor * @ param v2 divisor * @ return two parameter vendors */public static double div (double v1, double v2) {return div (v1, v2, DEFAULT_DIV_SCALE);}/*** provides (relatively) accurate Division operations. In case of division, the scale parameter determines * the precision, and the number is rounded down. * @ Param v1 divisor * @ param v2 divisor * @ param scale indicates the number of digits after the decimal point. * @ Return operator of two parameters */public static double div (double v1, double v2, int scale) {if (scale <0) {System. err. println ("division accuracy must be greater than 0! "); Return 0;} BigDecimal b1 = new BigDecimal (Double. toString (v1); BigDecimal b2 = new BigDecimal (Double. toString (v2); return (b1.divide (b2, scale, BigDecimal. ROUND_HALF_UP )). doubleValue ();}/*** calculate the Factorial! * @ Param n any int greater than or equal to 0 * @ return n! Value */public static BigInteger getFactorial (int n) {if (n <0) {System. err. println ("n must be greater than or equal to 0! "); Return new BigInteger ("-1 ");} else if (n = 0) {return new BigInteger (" 0 ");} // Replace the array with a string and construct BigInteger result = new BigInteger ("1"); for (; n> 0; n --) {// convert the number n into a string, and then construct a BigInteger object to multiply result = result with the existing result. multiply (new BigInteger (new Integer (n ). toString ();} return result;} public static void main (String [] args) {// What will be seen if we compile and run the following program? System. out. println (0.05 + 0.01); System. out. println (1.0-0.42); System. out. println (4.015*100); System. out. println (123.3/100); // 0.060000000000000005 // 0.5800000000000001 // 401.49999999999994 // 1.2329999999999999 // calculate the factorial. You can set n to a greater int n = 30; System. out. println ("Calculate the factorial of n" + n + "! = "+ BigNumber. getFactorial (n); // use double to construct BigDecimal bd1 = new BigDecimal (0.1); System. out. println ("(bd1 = new BigDecimal (0.1) =" + bd1.toString (); // use String to construct BigDecimal bd2 = new BigDecimal ("0.1"); System. out. println ("(bd2 = new BigDecimal (\" 0.1 \ ") =" + bd2.toString (); BigDecimal bd3 = new BigDecimal ("0.10 "); // The equals method compares whether two BigDecimal objects are equal, returns true if they are equal, and returns false System if not. Out. println ("bd2.equals (bd3) =" + bd2.equals (bd3); // false // The compareTo method compares the sizes of two BigDecimal objects. Equal returns 0, less than-1, if the value is greater than 1. System. out. println ("bd2.compareTo (bd3) =" + bd2.compareTo (bd3); // 0 // accurately calculates the System. out. println ("0.05 + 0.01 =" + BigNumber. add (0.05, 0.01); System. out. println ("1.0-0.42 =" + BigNumber. sub (1.0, 0.42); System. out. println ("4.015*100 =" + BigNumber. mul (4.015, 100); System. out. println ("123.3/100 =" + BigNumber. div (123.3, 100 ));}}

 

(1) Both BigInteger and BigDecimal are immutable. During each operation, a new object is generated, which may cause overhead, they are not suitable for a large number of mathematical calculations. We recommend that you use basic types such as long, float, and double for scientific or engineering computing.
BigInteger and BigDecimal are designed to accurately represent large integers and decimals. They are used in commercial computing.
(2) BigDecimal has four creation methods. Two of them are constructed using BigInteger, the other is constructed using double, and the other is constructed using String.
Avoid using double to construct BigDecimal, because some numbers cannot be exactly expressed with double, and the BigDecimal constructor is inaccurate. For example, the value of new BigDecimal (0.1) is 0.1000000000000000055511151231257827021181583404541015625.
The value obtained by using new BigDecimal ("0.1") is 0.1. Therefore, if exact calculation is required, use String to construct BigDecimal, avoiding double construction, although it looks simpler!
(3) The equals () method considers 0.1 and 0.1 to be equal, returns true, and considers 0.10 and 0.1 to be unequal, and returns false. The compareTo () method considers that 0.1 and 0.1 are equal, and 0.10 and 0.1 are also equal. Therefore, when comparing two BigDecimal values, use CompareTo() Instead of equals ().
(4) In other cases, decimal operations with any precision still cannot represent precise results. For example, dividing 1 by 9 produces an infinite number of decimal places. 111111 ....
For this reason, BigDecimal allows you to explicitly control rounding during Division operations.

 

Calculation Result:

 

0.06000000000000000000050.5800000000000001401.499999999999941.20000999999999999999 calculate the factorial of n 30! = 265252859812191058636308480000000 (bd1 = new BigDecimal (0.1) = 0.1000000000000000055511151231257827021181583404541015625 (bd2 = new BigDecimal ("0.1") = 0.1bd2.equals (bd3) = falsebd2.compareTo (bd3) = 00.05 + 0.01 = 0.061.0-0.42 = 1.20.000015*100 = 104.015123.3/100 = 223.3

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.