2 Division verbose, not just Python.

Source: Internet
Author: User

Integer divided by integer
After entering the python interactive mode (in the future, this kind of narrative may not be repeated, as long as you see >>>, it means that it is in interactive mode), practice the following operations:

>>> 2/5
0
>>> 2.0 / 5
0.4
>>> 2 / 5.0
0.4
>>> 2.0 / 5.0
0.4
Do you see it? The trouble comes out (this is in python2.x), according to the mathematical operation, the above four operation results should be 0.4. But the last three matches we saw, the first actually turned out to be 0. why?

Because, in python (strictly speaking, python2.x, python3 will change), there is a rule, like the division in 2/5, it is to be rounded (that is, decimals are removed, but not rounded). Divide 2 by 5, the quotient is 0 (integer), and the remainder is 2 (integer). Then if you use this form: 2/5, the calculation result is the integer of the quotient. Or it can be understood as: integer is divided by integer, the result is integer (quotient).

such as:

>>> 5/2
2
>>> 7/2
3
>>> 8/2
4
Note: The result is a quotient (integer), not the result with decimal places and rounded by "rounding". For example: 5/2, we get quotient 2, remainder 1, and finally 5/2 = 2. It is not a rounding of 2.5.

Divide floating point and integer
The format of this title is different from the above title. The above title is "Integer divided by integer". If the style is consistent, the title of this section should be "Floating point divided by integer", but no, now it is "Floating point number" Divide by integer ", which means:

Assumption: x divided by y. Where x may be an integer or a floating point number; y may be an integer or a floating point number.

Before drawing a conclusion, let's experiment first:

>>> 9.0 / 2
4.5
>>> 9 / 2.0
4.5
>>> 9.0 / 2.0
4.5

>>> 8.0 / 2
4.0
>>> 8 / 2.0
4.0
>>> 8.0 / 2.0
4.0
Induction, get the rule: no matter whether it is a divisor or a divisor, as long as one of the numbers is a floating point number, the result is a floating point number. Therefore, if the result of the division has a remainder, it will not be the same as before, but will return a floating point number, which is the same as the result of learning in mathematics.

>>> 10.0 / 3
3.3333333333333335
Isn't this a little bit weird, according to mathematics knowledge, it should be 3.333333 ..., followed by the 3 cycle. Then your computer can't stop, the full screen is 3. To avoid this, Python ended the loop arbitrarily, but, sadly, it did not terminate according to the "rounding" principle. Of course, there will be more exotic:

>>> 0.1 + 0.2
0.30000000000000004
>>> 0.1 + 0.1-0.2
0.0
>>> 0.1 + 0.1 + 0.1-0.3
5.551115123125783e-17
>>> 0.1 + 0.1 + 0.1-0.2
0.10000000000000003
More and more confused, why is the computer girl so confused on such a simple problem? Not computer girl confused, she is still smart. The reason is that in the conversion between decimal and binary, the computer girl uses binary to calculate. In the above example, we input decimal, she will convert the decimal number into binary, and then calculate. However, in the conversion, the floating-point number is converted into binary, there is a problem.

For example, decimal 0.1, converted to binary is: 0.0001100110011001100110011001100110011001100110011 ...

In other words, after conversion to binary, it will not be exactly equal to 0.1 decimal. At the same time, the number of digits stored by the computer is limited, so the above phenomenon occurs.

This kind of problem is not only in Python, all programming languages that support floating-point arithmetic will encounter it, it is not a Python bug.

Understand the cause of the problem, how to solve it? As far as Python's floating-point arithmetic is concerned, on most machines, the error of each calculation does not exceed 2 ** 53. This is sufficient for most tasks, but keep in mind that this is not a decimal algorithm, and each floating-point calculation may introduce a new rounding error.

In general, as long as the final displayed result is simply "rounded" to the desired number of decimal digits, the desired final result will be obtained.

For situations that require very precision, you can use the decimal module, which implements decimal operations suitable for accounting applications and applications requiring high precision. In addition, the fractions module supports another form of operation, which implements operations based on rational numbers (so numbers like 1/3 can be accurately represented). The highest requirement is to use the Numerical Python package provided by SciPy and other packages for math and statistics. Listing these things is just to make the function clear, there are many ways to solve the problem, and some of these will be used to solve the above problems later.

Regarding the problem of infinite loop decimals, I have a link to recommend to you, it is not as simple as imagined. Please read: Wikipedia's entry: 0.999 ..., will you have an in-depth experience?

Add a piece of information for interested friends to read: Floating-point number algorithm: disputes and restrictions

Python will always provide a variety of solutions to problems, this is her style.

Reference module to solve division-enable wheels
One of the most important reasons why Python is popular is that there are many wheels. This is a metaphor. Just like you want to run faster, what should I do? It is not necessary to practice running every day, but use wheels. Finding a bicycle is much faster. It ’s not fast enough. Change the battery car, change the car, and change the high-speed rail ... anyway, you can choose a lot. However, most of these things that make you run fast are not made by yourself. They are made by others and you use them. Even the two legs are thankful to parents for their gifts. It is precisely because there are many wheels and there are so many choices that you can enjoy at various speeds.

The wheel is a great invention of mankind.

Python is like this, there are various wheels, we just need to use. It's just that the names of those wheels in Python are not called bicycles or cars, and they are called "modules". Some people inherit the names of other languages, called "class libraries" and "classes. No matter what the name is. It is something that someone has made that we use it.

how to use? It can be used in two forms:

Form 1: import module-name. import followed by a space, then the module name, for example: import os
Form 2: from module1 import module11. module1 is a large module, and there are submodules module11 in it. I just want to use module11.
Not long-winded, experiment one:

>>> from __future__ import division
>>> 5/2
2.5
>>> 9/2
4.5
>>> 9.0 / 2
4.5
>>> 9 / 2.0
4.5
Note that after referring to a module, and then do the division, no matter what the situation is, you will get the result of the floating point number.

This is the power of the wheel.

remainder
When calculating 5/2 earlier, the quotient is 2, and the remainder is 1.

How to get the remainder? In python (actually in most languages), use the% symbol to get the remainder of dividing two numbers.

Experiment with the following operations:

>>> 5% 2
1
>>> 6% 4
2
>>> 5.0% 2
1.0
Symbol:% is the remainder of dividing two numbers (which can be integers or floating-point numbers).

Earlier I said that Python has a lot of wheels (modules) that people love, and she also has a wealth of built-in functions that will help us do many things. For example the function divmod ()

>>> divmod (5,2) # means 5 divided by 2, returns the quotient and remainder
(twenty one)
>>> divmod (9,2)
(4, 1)
>>> divmod (5.0,2)
(2.0, 1.0)
rounding
The last one, you must insist, today is indeed a bit long-winded. To achieve rounding, it is very simple, that is, the built-in function: round ()

Try it yourself:

>>> round (1.234567,2)
1.23
>>> round (1.234567,3)
1.235
>>> round (10.0 / 3,4)
3.3333
Simple. The simpler it is, the more careful you are. When you encounter the following situation, you are a bit skeptical:

>>> round (1.2345,3)
1.234 #should be: 1.235
>>> round (2.235,2)
2.23 #should be: 2.24
Haha, I found a bug in python, so excited.

Do n’t be so excited, if it ’s really a bug, it ’s so obvious that it ’s my turn. why? For a detailed explanation, see here, the following excerpt from the official document:

Note: The behavior of round () for floats can be surprising: for example, round (2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it's a result of the fact that most decimal fractions can't be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

It turned out that it was really my turn. In the final analysis, it is still the trouble caused by the conversion of decimals in floating-point numbers into binary.

It seems that the problem of division is over at this point, but it is far from there. However, as a beginner, it is enough. There are still a lot of topics left, such as how to deal with the problem of cyclic decimals. I will definitely not disappoint friends with exploration spirit. There is such a wheel in my github. If you want to study in depth, you can try it here.

2 The division is verbose, not just python.

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.