File: saveInverse.R

package info (click to toggle)
r-cran-mclogit 0.9.6-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 328 kB
  • sloc: makefile: 2
file content (21 lines) | stat: -rw-r--r-- 589 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
safeInverse <- function(x,tol=1e-7){
    tryCatch(solve(x),
             error=function(e){
                 warning(e$message,call.=FALSE,immediate.=TRUE)
                 warning("saveInverse: Using Moore-Penrose inverse",call.=FALSE,immediate.=TRUE)
                 moore.penrose(x,tol=tol)
             })
}

mach.eps <- .Machine$double.eps

moore.penrose <- function(x,tol=mach.eps*max(dim(x))*max(abs(d))){
    svd.x <- svd(x)
    d <- svd.x$d
    u <- svd.x$u
    v <- svd.x$v
    good <- abs(d) > tol
    id <- 1/d
    id[!good] <- 0
    v %*% diag(id,nrow=length(id)) %*% t(u)
}