Python tutorial: Python3 dividing the true division, division by truncation and rounding the comparative

Python tutorial: Python3 dividing the true division, division by truncation and rounding the comparative

There are partners want to see a message on Python3 compare different kinds of division rounding! coming! Here it over here!

In the Python3 , 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 the floor in a method analogous math module, 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
复制代码

Ceil method of the same module may be implemented in floating point math 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
复制代码

About True division, division, and cut down rounding contrast Python tutorials to begin to share so much, the partners are areas of doubt can leave a message Oh!


Reproduced in: https: //juejin.im/post/5cf60ece6fb9a07efe2da8c2

Guess you like

Origin blog.csdn.net/weixin_34124939/article/details/91473223