Integer and floating point numbers in Python

The arithmetic rules for integers and floating points in Python are the same as the four arithmetic rules in mathematics.

Basic calculations:

5 + 6 + 7   # ==> 18
4 * 4 - 6   # ==> 10
7.5 / 8 + 2.1   # ==> 3.0375

Like mathematical operations, parentheses can increase the priority. Only parentheses can be used, but they can be nested in many layers:

(2 + 2) * 3    # ==> 12
(2.2 + 5.3) / (1.5 * (9 - 4))    # ==> 1.0

The difference is that Python's integer operation result is an integer, and the floating point operation result is a floating point number:

1 + 2    # ==> 整数 3
1.0 + 1.0    # ==> 浮点数 2.0

The result of a mixed operation of integers and floating point numbers becomes floating point numbers:

5 + 2.0    # ==> 浮点数 7.0

Why should we distinguish between integer arithmetic and floating-point arithmetic? This is because the result of the integer operation is always accurate, and the result of the floating-point operation is not necessarily accurate, because no matter how large the computer's memory is, it can't accurately represent infinite loop decimals. For example, 0.1 is replaced by a binary representation of infinite loop decimals.

When the integer division operation encounters endless division, isn't the result a floating point number? Let's try it:

11 / 4    # ==> 2

Integer division of Python, even if the division is not endless, the result is still an integer, and the remainder is directly discarded. However, Python provides a remainder operation% to calculate the remainder:

11 % 4    # ==> 3

If we want to calculate the exact result of 11/4, according to the rule of "the result of mixed operation of integer and floating point is floating point", it is no problem to change one of the two numbers into a floating point and then calculate:

11.0 / 4    # ==> 2.75
Published 8 original articles · Likes2 · Visits 319

Guess you like

Origin blog.csdn.net/WHD1998/article/details/104787095