04-java High-precision Digital

Source: Internet
Author: User
Tags 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.

ImportJava.math.BigDecimal;ImportJava.math.BigInteger; Public classBigNumber {//Default division precision, that is, how many digits are reserved for the decimal pointPrivate Static Final intDefault_div_scale = 10;//This class cannot be instantiatedPrivateBigNumber () {}/*** provides accurate addition operations. * @paramv1 summand *@paramV2 Addend *@returntwo parameters of A and*/ Public Static DoubleAddDoubleV1,Doublev2) {BigDecimal B1=NewBigDecimal (double.tostring (v1)); BigDecimal B2=NewBigDecimal (Double.tostring (v2)); return(B1.add (B2)). Doublevalue ();}/*** provides accurate subtraction operations. * @paramv1 minuend *@paramv2 *@returnthe difference of two parameters*/ Public Static DoubleSubDoubleV1,Doublev2) {BigDecimal B1=NewBigDecimal (double.tostring (v1)); BigDecimal B2=NewBigDecimal (Double.tostring (v2)); return(B1.subtract (B2)). Doublevalue ();}/*** provides accurate multiplication operations. * @paramv1 by multiplier *@paramV2 Multiplier *@returnproduct of two parameters*/ Public Static DoubleMulDoubleV1,Doublev2) {BigDecimal B1=NewBigDecimal (double.tostring (v1)); BigDecimal B2=NewBigDecimal (Double.tostring (v2)); return(b1.multiply (B2)). Doublevalue ();}/*** Provide (relative) precise division operations, when there are no circumstances, the exact number of digits after the decimal point, after which the numbers are rounded. * @paramV1 Dividend *@paramv2 Divisor *@returntwo parameters of the quotient*/ Public Static DoubleDivDoubleV1,Doublev2) {   returnDiv (v1, v2, Default_div_scale);}/*** Provide (relative) accurate division operations. When the exception occurs, the scale parameter refers to the fixed precision, and the subsequent numbers are rounded. * @paramV1 Dividend *@paramv2 Divisor *@paramScale indicates the need to be accurate to several decimal places. * @returntwo parameters of the quotient*/ Public Static DoubleDivDoubleV1,DoubleV2,intScale ) {   if(Scale < 0) {System.err.println ("Division precision must be greater than 0!"); return0; } BigDecimal B1=NewBigDecimal (double.tostring (v1)); BigDecimal B2=NewBigDecimal (Double.tostring (v2)); return(B1.divide (B2, scale, BIGDECIMAL.ROUND_HALF_UP)). Doublevalue ();/*** Calculate factorial factorial! * @paramn any int* greater than or equal to 0@returnthe value of the n!*/ Public StaticBigInteger Getfactorial (intN) {if(N < 0) {System.err.println ("N must be greater than or equal to 0!" "); return NewBigInteger ("-1"); } Else if(n = = 0) {    return NewBigInteger ("0"); }   //Replace the array with a string and construct BigIntegerBigInteger result =NewBigInteger ("1");  for(; n > 0; n--) {    //after converting the number n to a string, construct a BigInteger object and multiply it with the existing result.result = Result.multiply (NewBigInteger (NewInteger (n). toString ())); }   returnresult;} Public Static voidMain (string[] args) {//what will we see 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//To calculate the factorial, you can set N to a larger   intn = 30; System.out.println ("Calculate the factorial of n + n +"! = " +bignumber.getfactorial (n)); //construct BigDecimal with doubleBigDecimal BD1 =NewBigDecimal (0.1); System.out.println ("(Bd1 = new BigDecimal (0.1)) =" +bd1.tostring ()); //construct BigDecimal with stringBigDecimal Bd2 =NewBigDecimal ("0.1"); System.out.println ("(Bd2 = new BigDecimal (\" 0.1\ ")) =" +bd2.tostring ()); BigDecimal Bd3=NewBigDecimal ("0.10"); //The equals method compares two BigDecimal objects for equality, returns true for equality, and not equal returns falseSystem.out.println ("bd2.equals (Bd3) =" + bd2.equals (Bd3));//false//The CompareTo method compares the size of two BigDecimal objects, returns 0 for equality, is less than 1, and is greater than return 1. System.out.println ("Bd2.compareto (Bd3) =" + Bd2.compareto (Bd3));//0//Perform accurate calculationsSystem.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 * =" + 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 basic types such as long,float,double to do scientific calculations or engineering calculations. The purpose of the
Design BigInteger and BigDecimal is to accurately represent large integers and decimals, which are used in commercial calculations.
      (2) BigDecimal There are 4 ways to make it, two of which are constructed with BigInteger, the other is constructed with a double, and one is constructed using string. The
should avoid using a 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
uses new BigDecimal ("0.1") to get a value of 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! = 265252859812191058636308480000000new BigDecimal (0.1)) = 0.1000000000000000055511151231257827021181583404541015625new BigDecimal ("0.1")) = 0.1  false  = 00.05 + 0.01 = 0.061.0-0.42 = 1.424.015 * 100 =104.015123.3/100 = 223.3

04-java High-precision Digital

Related Article

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.