1.9 Bounding the precision

Rounding, truncation, floor and ceiling functions are methods for writing numbers with bounded precision.

Rounding
To round a number to the \(k\)th decimal place, just look at the \(k\)+1th place. If the \(k\)+1th decimal place is 0, 1, 2, 3 or 4, the \(k\)th decimal place is retained; if the \(k\)+1th decimal place is 5, 6, 7, 8, or 9, add 1 to the \(k\)th decimal place.

Truncation
To truncate a number to the \(k\)th decimal place, simply eliminate the \(k\)+1th decimal place and its subsequent ones.

Floor and ceiling
Given \(x,y \in \mathbb{R}\) and \(m,n \in \mathbb{Z}\), floor and ceiling may be defined respectively by

\[\begin{equation} \lfloor x \rfloor = \max \{m \in \mathbb{Z} \mid m \le x\} \tag{1.3} \end{equation}\]

\[\begin{equation} \lceil x \rceil = \min \{n \in \mathbb{Z} \mid n \ge x\} \tag{1.4} \end{equation}\]

Exercise 1.6 Read Eq. (1.3) and (1.4) in full.

Example 1.15 Rounding and truncation.

Decimals Rounding Truncation
6 153.654321 153.654321
5 153.65432 153.65432
4 153.6543 153.6543
3 153.654 153.654
2 153.65 153.65
1 153.7 153.6
0 154 153
-1 150 150
-2 200 100

Floor and ceiling.

\(\lfloor 153.654321 \rfloor = 153\)
\(\lceil 153.654321 \rceil = 154\)

# Using base R
options(digits = 10) # Adjusting for 10-digit display (default: 7)
for(i in 6:-2){ 
  print(round(153.654321, dig = i)) # 'digits' decimal places
  }
## [1] 153.654321
## [1] 153.65432
## [1] 153.6543
## [1] 153.654
## [1] 153.65
## [1] 153.7
## [1] 154
## [1] 150
## [1] 200
trunc <- function(x, ..., dig = 0){
  base::trunc(x*10^dig, ...)/10^dig # Improving
} 
for(i in 6:-2){ 
  print(trunc(153.654321, dig = i)) # Precision of i decimal places
  }
## [1] 153.654321
## [1] 153.65432
## [1] 153.6543
## [1] 153.654
## [1] 153.65
## [1] 153.6
## [1] 153
## [1] 150
## [1] 100
floor(153.654321)
## [1] 153
ceiling(153.654321)
## [1] 154

Example 1.16 In Python.

import math

# Adjusting for 10-digit display
pd.set_option("display.precision", 10)

# 'digits' decimal places
for i in range(6, -3, -1):
print(round(153.654321, i))

# Enhancing the trunc() function
def trunc(x, dig=0):
return math.trunc(x * 10**dig) / 10**dig

# Precision of i decimal places
for i in range(6, -3, -1):
print(trunc(153.654321, i))

# Floor
print(math.floor(153.654321)) # Output: 153

# Roof
print(math.ceil(153.654321)) # Output: 154