Thinking logic of computer programs (5), thinking Logic

Source: Internet
Author: User

Thinking logic of computer programs (5), thinking Logic

Intuitive fact violations

The reason why a computer is called a "computing" machine is because it was invented mainly for computing. "computing" is of course its specialty. In everyone's impression, computing must be very accurate. But in fact, even in some basic decimal operations, the calculation results are not accurate.

For example:

float f = 0.1f*0.1f;System.out.println(f);

This result seems to be self-evident, it should be 0.01, but in fact, the screen output is 0.010000001, followed by 1 more.

How can a computer go wrong with such a simple operation?

Brief answer

In fact, it is not the operation itself that will go wrong, but the computer cannot accurately represent a large number, such as 0.1.

A computer uses a binary format to store decimal places. This binary format cannot accurately represent 0.1. It can only represent a number that is very close to 0.1 but not equal to 0.1.

Numbers cannot be expressed accurately. It is not surprising that the operation results on inaccurate numbers are inaccurate.

0.1 why cannot it be accurately expressed? It is acceptable in the decimal world, but not in the binary world. Before speaking of binary, let's take a look at the familiar decimal.

In fact, decimal can only represent the number of times and numbers that can be expressed as 10, such as 12.345, which actually represents: 1*10 + 2*1 + 3*0.1 + 4*0.01 + 5*0.001, similar to the integer representation, each location after the decimal point also has a single-digit permission, from left to right, 0.1, 0.01, 0.001 ,... 10 ^ (-1), 10 ^ (-2), 10 ^ (-3 ).

Many decimal digits cannot be exactly represented. For example, if 1/3 is reserved for three decimal places, the decimal value is 0.333, but no matter how many decimal places are retained, use 0.333 for calculation. For example, multiply by 3. The expected result is 1, but it is actually 0.999.

Binary is similar, but binary can only represent the number of times and numbers that can be expressed as 2. Here are some examples of the power of 2:

Power of 2 Decimal
2 ^ (-1) 0.5
2 ^ (-2) 0.25
2 ^ (-3) 0.125
2 ^ (-4) 0.0625

The number of vertices that can be exactly expressed as the sum of a power of 2 can be precisely expressed, while other numbers cannot be exactly expressed.

Why must we use binary?

Why can't we use the familiar decimal format? At the very bottom layer, the electronic components used by computers can only represent two States, usually low voltage and high voltage, corresponding to 0 and 1. It is easy to build hardware devices and perform operations based on these electronic devices using binary. If you want to use decimal, the hardware will be much more complicated and inefficient.

What is the accuracy of fractional calculation?

If you write a program for testing, you will find that some calculation results are accurate. For example, I use Java to write:

System.out.println(0.1f+0.1f); System.out.println(0.1f*0.1f);

Output in the first line is 0.2, and output in the second line is 0.010000001. According to the above statement, the result of the first line should be incorrect?

In fact, this is just the illusion that the Java language has caused us, and the calculation results are not accurate, but because the results are close enough to 0.2, in the output, java chooses to output 0.2, a seemingly simplified number, instead of a decimal number with many zeros in the middle.

When the error is small enough, the result looks accurate, but the inaccuracy is actually the norm.

How to deal with inaccurate computing

What should I do if the calculation is not accurate? In most cases, we don't need such high precision. We can rounding it in, or keep a fixed number of decimal places in the output.

If you really need high precision, one method is to convert decimals into integers for computation, and then convert them to decimals after the computation. The other method is generally to use the decimal data type, there is no uniform specification. in Java, there is a BigDecimal algorithm, which is more accurate but less efficient. This section will not be detailed.

Binary representation

We have been using the word "decimal" to represent the float and double types. In fact, this is not rigorous. "decimal" is a word used in mathematics. in computers, we generally say "floating point number ". Float and double are called floating-point data types, while decimal operations are called floating-point operations.

Why is it a floating point number? This is because the decimal point in the binary representation of the decimal point is not fixed, but floating.

We still use a 10-digit analogy. The 10-digit notation has a scientific representation. For example, if the number 123.45 is directly written in this way, it is a fixed notation. If scientific notation is used, only one digit is reserved before the decimal point. It can be written as 1.2345E2, that is, 1.2345*(10 ^ 2). That is, in the scientific representation, two decimal points are moved to the left.

In binary format, decimal places are represented. Similar scientific notation is used, such as m * (2 ^ e ). M is called the ending number, and e is called the index. An index can be true or negative. A negative index indicates a small number close to 0. In binary, it represents the ending part and the exponent part separately. In addition, there is a sign bit that represents positive and negative.

Almost all hardware and programming languages share the same binary format for decimal numbers. This format is a standard, known as the IEEE 754 standard. It defines two formats, one is 32-bit, corresponding to Java float, and the other is 64-bit, corresponding to Java's double.

In the 32-bit format, 1 represents a symbol, 23 represents the ending number, and 8 represents an index. In the 64-bit format, one digit represents the symbol, 52 digits represents the ending number, and 11 digits represent the index.

In both formats, apart from representing normal numbers, the standard also specifies some special binary forms to represent some special values, such as negative infinity, positive infinity, 0, naN (non-numeric value, for example, 0 multiplied by infinity ).

The IEEE 754 standard has some complicated details that seem hard to understand for the first time and is not commonly used in daily applications.

If you want to view the binary format of a floating point number, you can use the following code in Java:

Integer.toBinaryString(Float.floatToIntBits(value))Long.toBinaryString(Double.doubleToLongBits(value));

Summary

Why is an error in decimal calculation? The reason is: many decimal computers cannot be exactly represented.

The Basic Thinking of computers is binary, so unexpected, reasonable!

In the previous section, we talked about the binary of integers and decimal places.

What about the characters and text? What is encoding? What is the cause of garbled code?

----------------

To learn more about Java programming and the nature of computer technology, read the latest article and follow the official code "lauma programming" (scan the QR code below. Original article, retain all copyrights.

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.