Use Java to accurately calculate floating point numbers

Source: Internet
Author: User
Tags mul
Document directory
  • HTML tags and JavaScript tutorial

HTML tags and JavaScript tutorial


Use Java to accurately calculate floating point numbers

Question:
What do we see if we compile and run the following program?
Public class test {
Public static void main (string ARGs []) {
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 );
}
};
You are not mistaken! The result is indeed
0.060000000000000005
0.5800000000000001
401.49999999999994
1.2329999999999999
The float and double types of simple floating point numbers in Java cannot be computed. Not only Java, but also many other programming languages
This problem also exists in the language. In most cases, the calculation result is accurate, but you can try it several times.
A loop. Now we finally understand why we need BCD code.
This problem is quite serious. If you have 9.999999999999 yuan, your computer will not think you can buy 10 yuan
.
Some Programming Languages provide special currency types to handle this situation, but Java does not. Now let's see
See how to solve this problem.
Rounding
Our first response was rounding. The round method in the math class cannot be set to retain a few decimal places.
Can be like this (retain two digits ):
Public double round (double value ){
Return math. Round (value * 100)/100.0;
}
Unfortunately, the code above does not work normally. If you pass 4.015 to this method, it will return 4.01 instead
4.02, as we can see above
4.015*100 = 401.49999999999994
Therefore, if we want to perform precise rounding, we cannot use simple types for any operation.
Java. Text. decimalformat cannot solve this problem either:
System. Out. println (New java. Text. decimalformat ("0.00"). Format (4.025 ));
The output is 4.02
Bigdecimal
This principle is also mentioned in objective java. Float and double can only be used for scientific computing or
It is Engineering Computing. In commercial computing, we use Java. Math. bigdecimal. Bigdecimal: a total of four values can be created.
Method, we don't care about the two that can be created using biginteger, so there are two more, they are:
Bigdecimal (double Val)
Translates a double into a bigdecimal.
Bigdecimal (string Val)
Translates the string repre sentation of a bigdecimal into a bigdecimal.
The Brief description of the above API is quite clear, and it is usually easier to use the above one.
We may use it if we don't want it. What's the problem? Which of the above is sufficient when a problem occurs?
The detailed description of the Creation method contains the following section:
Note: The results of this constructor can be somewhat unpredictable. One might
Assume that new bigdecimal (. 1) is exactly equal to. 1, but it is actually
Equal to. 1000000000000000055511151231257827021181583404541015625. This is so
Because. 1 cannot be represented exactly as a double (or, for that matter,
A binary fraction of any finite length). Thus, the long value that is being
Passed in to the constructor is not exactly equal to. 1, appearances
Nonwithstanding.
The (string) constructor, on the other hand, is perfectly predictable: New
Bigdecimal (". 1") is exactly equal to. 1, as one wowould would perform CT. Therefore, it is
Generally recommended that the (string) constructor be used in preference
This one.
It turns out that if we need precise calculation, we have to use string to create bigdecimal! In objective Java,
The example in this book uses string to create bigdecimal, but this is not emphasized in the book.
A small mistake.
Solution
Now we can solve this problem. The principle is to use bigdecimal and must use string to create it.
But imagine, if we want to do an addition operation, we need to convert two floating point numbers into strings first, and then
Bigdecimal. Call the add method on one of them, input another as a parameter, and then calculate the result.
(Bigdecimal) and then converts it to a floating point number. Can you endure this cumbersome process? Below we provide a tool
Arith class to simplify operations. It provides the following static methods, including addition, subtraction, multiplication, division, and rounding:
Public static double add (double V1, double V2)
Public static double sub (double V1, double V2)
Public static double MUL (double V1, double V2)
Public static double Div (double V1, double V2)
Public static double Div (double V1, double V2, int scale)
Public static double round (Double V, int scale)
Appendix
Source File Arith. Java:
Import java. Math. bigdecimal;
/**
* Because Java's simple types cannot accurately perform floating-point operations, this tool provides
* A real floating point number operation, including addition, subtraction, multiplication, division, and rounding.
*/
Public class Arith {
// Default division operation precision
Private Static final int def_div_scale = 10;
// This class cannot be instantiated
Private Arith (){
}
/**
* Provides precise addition operations.
* @ Param V1 add count
* @ Param V2 addend
* @ Return the sum of the two parameters
*/
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 operations.
* @ 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 precise multiplication.
* @ Param V1 Multiplier
* @ Param V2 Multiplier
* @ Return the 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) accurate Division operations, accurate
* 10 digits after the decimal point, and the digits after the decimal point are rounded down.
* @ Param V1 Divisor
* @ Param V2 Divisor
* @ Return parameter vendors
*/
Public static double Div (double V1, double V2 ){
Return Div (V1, V2, def_div_scale );
}
/**
* Provides (relatively) accurate Division operations. In case of division, the scale parameter indicates
* Set the precision. The number is rounded down.
* @ Param V1 Divisor
* @ Param V2 Divisor
* @ Param scale indicates the number of digits after the decimal point.
* @ Return parameter vendors
*/
Public static double Div (double V1, double V2, int scale ){
If (scale <0 ){
Throw new illegalargumentexception (
"The scale must be a positive integer or zero ");
}
Bigdecimal b1 = new bigdecimal (double. tostring (V1 ));
Bigdecimal b2 = new bigdecimal (double. tostring (V2 ));
Return b1.divide (B2, scale, bigdecimal. round_half_up). doublevalue ();
}
/**
* Provides precise rounding of decimal places.
* @ Param V refers to the number rounded up.
* @ Param scale: number of digits after the decimal point
* @ Return returns the result after rounding.
*/
Public static double round (Double V, int scale ){
If (scale <0 ){
Throw new illegalargumentexception (
"The scale must be a positive integer or zero ");
}
Bigdecimal B = new bigdecimal (double. tostring (V ));
Bigdecimal one = new bigdecimal ("1 ");
Return B. Divide (one, scale, bigdecimal. round_half_up). doublevalue ();
}
};
 

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.