Introduction of several divisions in python3 and different display of decimals

  • 2021-10-11 18:54:25
  • OfStack

Environment: python 3.6. 1

1. Division in python3

In python3, when division is encountered in an arithmetic expression, there are two different division methods to choose from, namely/and//. Different expressions have different running results, which are explained in detail here.

1,/Operator (True Division)

In python3, the/operator always runs true division when it is in an expression, and the result remains decimal regardless of the type accepted.


print(4/2) # 2.0
print(4/2.0) # 2.0
print(5/2) # 2.5

2. The//Operator (Floor Division)

In python3, the//operator always runs Floor division when it is in an expression, and the fractional part of the result is retained only when the accepted type contains floating-point type.


print(4//2.0) # 2.0
print(4//2) # 2
print(5//2) # 2

2. Different display of decimals

There are many different displays of decimals, such as floor, trunc and round

floor, truncates the decimal down to its lower level, which is the largest integer less than the decimal. And valid for negative numbers.


import math
print(math.floor(2.5)) # 2
print(math.floor(-2.5)) # -3

trunc, true truncation, true truncation of the decimal, so when the decimal greater than 0, the effect is the same as floor.


import math
print(math.trunc(2.5)) # 2
print(math.trunc(-2.5)) # -2

round, formatted by 1 decimal, is similar to approximately in primary school mathematics. round is a built-in function and does not require pouring.


print(round(2.567)) # 3
print(round(2.467)) # 2
print(round(2.567, 2)) # 2.57

Supplement: Division of python2 and python3


python2 : 5/3=1  "Rounding down - Except " 
python3 : 5/3=1.6666666666666667 "Precision-division" 
 
python2 : 5//3=1  "Rounding down - Except " 
python3 : 5//3=1  "Rounding down - Except " 

Related articles: