python integer and floating point numbers

Integers and floating point numbers in Python

Python supports four arithmetic operations on integers and floating-point numbers. The arithmetic rules are exactly the same as the mathematical four rules.

Basic operation:

1 + 2 + 3 # ==> 6
4 * 5 - 6 # ==> 14
7.5 / 8 + 2.1 # ==> 3.0375

Use parentheses to increase the priority, which is exactly the same as mathematical operations. Note that only parentheses can be used, but parentheses can be nested in many layers:

(1 + 2) * 3     # ==> 9 
(2.2 + 3.3) / (1.5 * (9 - 0.3))     # ==> 0.42145593869731807

The difference between math and math is that Python’s integer operation result is still an integer, and the floating-point operation result is still a floating-point number:

1 + 2 # ==> integer 3
1.0 + 2.0 # ==> Floating point number 3.0

But the result of a mixture of integer and floating point numbers becomes a floating point number:

1 + 2.0 # ==> floating point number 3.0

Why distinguish between integer and floating point arithmetic? This is because the result of integer arithmetic is always accurate, and the result of floating-point arithmetic is not necessarily accurate, because the computer memory is too large, and can not accurately represent infinite loop fractions, such as 0.1 switching to binary representation is an infinite loop fraction.

When the division of the integer encounters the inexhaustible, is the result not a floating point number? Let’s try it out:

11 / 4 # ==> 2

What surprised many beginners is that Python’s integer division, even if it is not exhausted, the result is still an integer, and the remainder is thrown away. However, Python provides a remainder of the operation % to calculate the remainder:

11 % 4 # ==> 3

If we want to calculate the exact result of 11 / 4, according to the “the result of the mixed integer and floating-point number is floating-point number” rule, it is no problem to convert one of the two numbers into a floating-point number and then operate:

11.0 / 4 # ==> 2.75

Leave a Reply

Your email address will not be published. Required fields are marked *