System.out.println( 0.1 + 0.7 );
|
And each of the decimal places also has a weight. If we switch to scientific notation, then
Although most of them can be accurately represented in base 10, many of them can’t be accurately represented in binary. For example, 10/3 is approximately 3.33, no matter how many decimal places there are, 10/3 can’t be accurately represented, only approximately 3.33. In fact, binary is similar, binary decimal notation in scientific notation, first look at 2 to the x power corresponding to the base 10 data.
So we can understand the decimal value 0.1 = 1*2^(-?). + 1 * 2 ^ (-)? + 1 * 2 ^ (-)? +… No matter how you add them up, you end up getting infinitely close to 0.1, not really 0.1. One might ask that the program does display 0.1, which is an illusion given by the Java language, and that the calculation is actually inaccurate, but because the result is close enough to 0.1, Java chose to print 0.1, which looks like a very compact number, rather than a decimal with lots of zeros in between. When the error is small enough, the result looks accurate, but inaccuracy is the norm. Binary represents decimal, also uses the scientific calculation method, such as m*(2^e). M is called the mantissa and e is called the exponent. Exponents can be positive or negative, and floating point numbers in computers represent the tail and exponent separately, plus a sign bit. The binary format for decimals is the same for almost all hardware and languages. This is a standard called IEEE754, which defines two formats: 32-bit for float and 64-bit for double, where the 1 bit represents the symbol. The 23 digits indicate the mantissa and the 8 digits indicate the exponent. In 64-bit format, 1 bit represents a symbol, 52 bits represent a mantissa, and 11 bits represent an exponent. There are also some complicated details in IEEE754 that are difficult to understand and not commonly used, so I won’t cover them in this article for now. Some people also ask, why does the underlying data of the computer have to be represented in binary? Computer is nothing more than an electrical appliance, there are countless resistors and capacitors, when the computer through alternating current, encountered capacitor is low voltage with 0, encountered resistance is high voltage with 1, so the bottom of the computer can only be binary, because he can only represent high and low voltage. This is analog and digital circuits.
1
2
3
4
5
6
|
// Take the sum of 1-9 and divide by 10
int sum = 0 ;
for ( int i = 1 ; i <= 9 ; i++) {
sum+=i;
}
System.out.println(sum/ 10.0 ); / / 4.5
|
01
02
03
04
05
06
07
08
09
10
|
package cam.itheima.demo;
import java.math.BigDecimal;
public class Demo5 {
public static void main(String[] args) {
BigDecimal bd1 = new BigDecimal( "0.1" );
BigDecimal bd2 = new BigDecimal( "0.7" );
BigDecimal sum = bd1.add(bd2);
System.out.println(sum);
}
}
|