Python3 dividing the true division, division by truncation and rounding the comparative

Outline

In Python3, the mathematical operations division is divided into two, namely "true division", that is, regardless of any type of result of the division will retain the decimal point, and our actual math results are consistent, and "truncated division", the the results, whether the fractional part omitted results are divided by any type, the remaining minimum integer divisible portion. The following is the basic form for division of:

# 真除法
X / Y
# 截断除法
X // Y

True division

X = 8
Y = 2
Z = 3

print(X / Y)
print(X / Z)

Sample results:

4.0
2.6666666666666665

The results show that regardless of the type of division true the operand of which returns a floating-point result of the division result.

Truncated division

X = 8
Y = 2
Z = 3
S = -8

print(X // Y)
print(X // Z)
print(S // Y)
print(S // Z)

Sample results:

4
2
-4
-3

We can see from the examples, the division by truncation is not really directly remove decimals, but a similar module mathin floorthe method, i.e., rounding down, rounding and negative values of this embodiment also.

import math

math.floor(2.0)
math.floor(2.6666666666666665)
math.floor(-2.0)
math.floor(-2.6666666666666665)

Sample results:

2
2
-2
-3

The same module mathin ceilthe methods may be implemented floating point rounding.

import math

print(math.ceil(2.0))
print(math.ceil(2.6666666666666665))
print(math.ceil(-2.0))
print(math.ceil(-2.6666666666666665))

2
3
-2
-2

We will certainly encounter many difficulties when learning python, as well as the pursuit of new technologies, here's what we recommend learning Python buckle qun: 784758214, here is the python learner gathering place! ! At the same time, he was a senior development engineer python, python script from basic to web development, reptiles, django, data mining and other projects to combat zero-based data are finishing. Given to every little python partner! Daily share some methods of learning and the need to pay attention to small details

Click: Python technology sharing

Guess you like

Origin blog.csdn.net/zhizhun88/article/details/91465592