Debian Codegraph @

R/relErr.R

raw
1 ## The relative error typically returned by all.equal.numeric(),
2 ## "kept as simple as possible"
3 relErr <- function(target, current) { ## make this work, also for 'Matrix' ==> no mean() ..
4 n <- length(current)
5 if(length(target) < n) # (as we don't use mean())
6 target <- rep(target, length.out = n)
7 sum(abs(target - current)) / sum(abs(target))
8 }
9
10 ## Componentwise aka "Vectorized" relative error:
11 ## Must not be NA/NaN unless one of the components is ==> deal with {0, Inf, NA}
12 relErrV <- function(target, current, eps0 = .Machine$double.xmin) {
13 n <- length(target <- as.vector(target))
14 ## assert( <length current> is multiple of <length target>) :
15 lc <- length(current)
16 if(!n) {
17 if(!lc) return(numeric()) # everything length 0
18 else stop("length(target) == 0 differing from length(current)")
19 } else if(!lc)
20 stop("length(current) == 0 differing from length(target)")
21 ## else n, lc > 0
22 if(lc %% n)
23 stop("length(current) must be a multiple of length(target)")
24 recycle <- (lc != n) # explicitly recycle
25 R <- if(recycle)
26 target[rep(seq_len(n), length.out=lc)]
27 else
28 target # (possibly "mpfr")
29 R[] <- 0
30 ## use *absolute* error when target is zero {and deal with NAs}:
31 t0 <- abs(target) < eps0 & !(na.t <- is.na(target))
32 R[t0] <- current[t0]
33 ## absolute error also when it is infinite, as (-Inf, Inf) would give NaN:
34 dInf <- is.infinite(E <- current - target)
35 R[dInf] <- E[dInf]
36 useRE <- !dInf & !t0 & (na.t | is.na(current) | (current != target))
37 R[useRE] <- (current/target)[useRE] - 1
38 ## preserve {dim, dimnames, names} from 'current' :
39 if(!is.null(d <- dim(current)))
40 array(R, dim=d, dimnames=dimnames(current))
41 else if(!is.null(nm <- names(current)) && is.null(names(R))) # not needed for mpfr
42 `names<-`(R, nm)
43 else R
44 }