rel_diff | R Documentation |
Calculate absolute differences with abs_diff()
and
relative differences with rel_diff()
rel_diff(x, y, scale = NA_real_)
abs_diff(x, y)
x |
A double vector. |
y |
A double vector. |
scale |
A double vector.
When |
The relative difference in this package is calculated as
abs_diff(x / scale, y / scale)
except in the case that both
x
and y
are approximately 0 which results in 0.
The scale is calculated as max(abs(x), abs(y))
by default when
scale is NA
.
This has the nice property of making rel_diff()
a commutative function
in which the order of the arguments doesn't matter. You can of course
supply your own scale.
For info, an R way to calculate the relative difference is as follows
r_rel_diff <- function(x, y){ ax <- abs(x) ay <- abs(y) scale <- pmax(ax, ay) ifelse( ax < sqrt(.Machine$double.eps) & ay < sqrt(.Machine$double.eps), 0, abs_diff(x / scale, y / scale) ) }
This is much slower than the C++ written rel_diff
.
all.equal()
As mentioned above, unlike base::all.equal()
, rel_diff()
is commutative.
To match the relative difference calculation used by all.equal()
,
simply set scale = x
.
Therefore, to make a vectorised binary version of all.equal()
,
we can write for example the following:
all.equal2 <- \(x, y, tol = get_tolerance()) rel_diff(x, y, scale = x) < tol
A numeric vector.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.