Python supports four blending of integers and floating-point numbers directly, and the arithmetic rules are exactly the same as the arithmetic rules in mathematics.
Basic operations:
1 + 2 + 3 # ==> * 5-6 # ==> 147.5/8 + 2.1 # ==> 3.0375
Using parentheses can elevate precedence, which is exactly the same as math, and note that only parentheses can be used, but parentheses may nest many layers:
(1 + 2) * 3 # ==> 9 (2.2 + 3.3)/(1.5 * (9-0.3)) # ==> 0.42145593869731807
Unlike mathematical operations, the result of a Python integer operation is still an integer, and the result of the floating-point operation is still a floating-point number:
1 + 2 # ==> integer 31.0 + 2.0 # ==> Floating point 3.0
But the result of mixed integer and floating-point numbers becomes a floating-point number:
1 + 2.0 # ==> Floating point 3.0
Why do you differentiate between integer and floating-point arithmetic? This is because the result of an integer operation is always accurate, and the result of the floating-point operation is not necessarily accurate, because the computer memory is large, and can not accurately represent an infinite loop of decimals, for example, a binary 0.1
representation is an infinite loop decimal.
Is the result not a floating-point number when the division operation of the integer is encountered in addition to the endless? Let's try it out:
11/4 # ==> 2
To the surprise of many beginners, the integer division of Python, even if it is not endless, the result is still an integer, the remainder is directly thrown away. However, Python provides a calculation of the remainder of the operation% that can be computed:
% 4 # ==> 3
If we want to calculate the exact result of 11/4, the "integer and floating-point mixed operation results are floating-point number" law, the two numbers of one into a floating point and then the operation is no problem:
11.0/4 # ==> 2.75
The above content transferred from MU class net, only for individual study!
Integers and floating-point numbers in Python