trunc()
function takes a single numeric argument x and returns a numeric vector containing the integers formed by truncating the values in x toward 0.trunc(x, ...)
The parameters are:
-
x
: numeric vectorx = seq(-3,3, by = 0.5)
x
## [1] -3.0 -2.5 -2.0 -1.5 -1.0 -0.5 0.0 0.5 1.0 1.5 2.0 2.5 3.0
trunc(x)
## [1] -3 -2 -2 -1 -1 0 0 0 1 1 2 2 3
trunc()
function returns the integer value most near to 0. For example, if we apply the trunc()
function to 3.5 the result will be 3, and if we apply the function to -3.5 the result will be -3 (not -4).
Difference between
trunc()
and floor()
functions:floor()
function takes a single numeric argument x and returns a numeric vector containing the largest integers not greater than the corresponding elements of x.floor(x)
values = seq(-3,3, by = 0.5)
values
## [1] -3.0 -2.5 -2.0 -1.5 -1.0 -0.5 0.0 0.5 1.0 1.5 2.0 2.5 3.0
trunc(values)
## [1] -3 -2 -2 -1 -1 0 0 0 1 1 2 2 3
floor(values)
## [1] -3 -3 -2 -2 -1 -1 0 0 1 1 2 2 3
par(mfrow = c(1,2))
x = c(1:13)
y1 = trunc(values)
y2 = floor(values)
plot(x, values,ylim = range(c(-4,4)),col = 'darkturquoise', type = 'l')
points(x, y1, col = 'darkviolet', type = 'l')
legend("topleft", inset=.05, c("No function","Trunc()"), fill=c('darkturquoise','darkviolet'))
plot(x, values,ylim = range(c(-4,4)),col = 'darkturquoise', type = 'l')
points(x, y2, col = 'deeppink', type = 'l')
legend("topleft", inset=.05, c("No function","Floor()"), fill=c('darkturquoise','deeppink'))
From the plots we see that the function
trunc()
returns the integer closer to 0 while floor()
function returns the integer smaller than the original value.
No comments:
Post a Comment