1.8 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}\]
Example 1.7 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
## [1] 153
## [1] 154
## [1] 153.6543
## [1] 153.65
## [1] 154
## [1] 200