Java High-precision large numeric operations

Source: Internet
Author: User
Tags array to string mul

In order to solve the problem that the Java basic data type will overflow and be computationally inaccurate during operation. Java provides two classes of BigInteger and BigDecimal, specifically for high-precision operations. Anything that can be done with int or float can be done with BigInteger and BigDecimal, except that you have to change the method call instead of using the operator.
High Precision integer BigInteger
BigInteger supports integers of arbitrary precision, which means that we can accurately represent an integer value of any size, and that no information is lost during the operation;
High-precision floating-point number BigDecimal

It can represent arbitrary-precision decimals and calculate them. Because BigDecimal objects are immutable, each of these methods produces a new BigDecimal object. Therefore, because of the overhead of creating objects, 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 precision, that is, how many bits of private static are reserved Final int Default_div_scale = 10;//This class cannot instantiate private BigNumber () {}/** * provides exact addition operations. * @param v1 summand * @param v2 Addend * @return two parameters and */public static double add (double v1, double v2) {BigDecimal B1 = new B   Igdecimal (double.tostring (v1));   BigDecimal b2 = new BigDecimal (double.tostring (v2)); Return (B1.add (B2)). Doublevalue ();} /** * provides accurate subtraction operations. * @param v1 minuend * @param v2 meiosis * @return Two parameter difference */public static double sub (double V1, double v2) {BigDecimal B1 = new B   Igdecimal (double.tostring (v1));   BigDecimal b2 = new BigDecimal (double.tostring (v2)); Return (B1.subtract (B2)). Doublevalue ();} /** * provides accurate multiplication operations. * @param v1 by multiplier * @param v2 multiplier * @return Two parameters of the product */public static double Mul (double v1, double v2) {BigDecimal B1 = new B   Igdecimal (double.tostring (v1));   BigDecimal b2 = new BigDecimal (double.tostring (v2)); Return (b1.multiply (B2)). Doublevalue ();} /** * provides (relative) accurate Division operationsThe number of digits after the decimal point, after which the numbers are rounded up, when there are no more than an endless amount of cases. * @param v1 Dividend * @param v2 divisor * @return two parameters of quotient */public static double div (double v1, double v2) {return div (v1, v2, DE Fault_div_scale);} /** * provides (relative) accurate division operations. When the exception occurs, the scale parameter refers to the fixed precision, and the subsequent numbers are rounded. * @param v1 Dividend * @param v2 divisor * @param scale indicates the need to be accurate to several decimal places. * @return two parameters of quotient */public static double div (double v1, double v2, int scale) {if (Scale < 0) {System.err.println    ("Division precision 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 factorial factorial! * @param n any value greater than or equal to 0 of int* @return n! */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");   }//convert array to string and construct BigInteger BigInteger result = new BigInteger ("1"); for (; n > 0; n--) {//Converts the number N to a string, a BigInteger object is constructed, with the existing results multiplied by result = result.multiply (new BigInteger (new Integer (n). toString ())); } return result;   public static void Main (string[] args) {//If we compile and run the following program will see what?   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 factorial to set N to Greater   int n = 30; System.out.println ("Calculate the factorial of n + n +"!)   = "+ bignumber.getfactorial (n));   Construct BigDecimal BigDecimal bd1 = new BigDecimal (0.1) with double;   System.out.println ("(Bd1 = new BigDecimal (0.1)) =" + bd1.tostring ());   Constructed with string BigDecimal 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 two BigDecimal objects for equality, returns true for equality, and not equal returns False System.out.println ("bd2.equals (Bd3) =" + bd2.equals (BD3));// False//compareThe to method compares the size of two BigDecimal objects, returns 0 for equality, less than return-1, and is greater than 1. System.out.println ("Bd2.compareto (Bd3) =" + Bd2.compareto (Bd3)),//0//For precise calculation System.out.println ("0.05 + 0.01 =" + Bi   Gnumber.add (0.05, 0.01));   System.out.println ("1.0-0.42 =" + bignumber.sub (1.0, 0.42));   SYSTEM.OUT.PRINTLN ("4.015 * =" + Bignumber.mul (4.015, 100));   System.out.println ("123.3/100 =" + bignumber.div (123.3, 100)); }}

(1) BigInteger and BigDecimal are immutable (immutable), each step of the operation, will produce a new object, because the creation of objects will incur overhead, they are not suitable for a large number of mathematical calculations, should try to use Long,float, Double and other basic types do scientific calculations or engineering calculations.
The purpose of designing BigInteger and BigDecimal is to accurately represent large integers and decimals, which are used in commercial calculations.
(2) There are 4 BigDecimal, two of which are constructed with BigInteger, the other is constructed with a double, and one is constructed using string.
You should avoid using double to construct BigDecimal, because: some numbers are not exactly represented by a double, and are not accurate when passed to the BigDecimal construction method. For example, new BigDecimal (0.1) Gets a value of 0.1000000000000000055511151231257827021181583404541015625.
The value obtained with new BigDecimal ("0.1") is 0.1. So, if you need a precise calculation, construct the BigDecimal with a string and avoid constructing it with a double, even though it looks simpler!
(3) The Equals () method considers that 0.1 and 0.1 are equal, returns True, and that 0.10 and 0.1 are unequal, and the result returns false. The method CompareTo () thinks that 0.1 is equal to 0.1, and 0.10 is equal to 0.1. Therefore, when comparing two bigdecimal values from a numeric value, you should use compareTo() instead of equals ().
(4) In other cases, fractional operations with arbitrary precision still do not represent precise results. For example, 1 divided by 9 will produce an infinite loop of decimals. 111111 ....
For this reason, BigDecimal allows you to explicitly control rounding when you perform a division operation.

Result of Operation:

0.0600000000000000050.5800000000000001401.499999999999941.2329999999999999 calculates 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.424.015 * 100 =104.015123.3/100 = 223.3

Java High-precision large numeric operations

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.