1#  File src/library/base/R/det.R
2#  Part of the R package, https://www.R-project.org
3#
4#  Copyright (C) 1995-2012 The R Core Team
5#
6#  This program is free software; you can redistribute it and/or modify
7#  it under the terms of the GNU General Public License as published by
8#  the Free Software Foundation; either version 2 of the License, or
9#  (at your option) any later version.
10#
11#  This program is distributed in the hope that it will be useful,
12#  but WITHOUT ANY WARRANTY; without even the implied warranty of
13#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14#  GNU General Public License for more details.
15#
16#  A copy of the GNU General Public License is available at
17#  https://www.R-project.org/Licenses/
18
19## det now uses Lapack and an LU decomposition.  The method argument is
20##     no longer used.
21## S-plus' Matrix pkg has arg. "logarithm = TRUE" and returns list
22##        (which is necessary for keeping the sign when taking log ..)
23## S-plus v 6.x has incorporated the Matrix pkg det as determinant
24
25det <- function(x, ...)
26{
27    z <- determinant(x, logarithm = TRUE, ...)
28    c(z$sign * exp(z$modulus))
29}
30
31determinant <- function(x, logarithm = TRUE, ...) UseMethod("determinant")
32
33determinant.matrix <- function(x, logarithm = TRUE, ...)
34{
35    if ((n <- ncol(x)) != nrow(x))
36        stop("'x' must be a square matrix")
37    if (n < 1L)
38	return(structure(list(modulus =
39			      structure(if(logarithm) 0 else 1,
40					logarithm = logarithm),
41			      sign = 1L),
42			 class = "det"))
43    if (is.complex(x))
44        stop("'determinant' not currently defined for complex matrices")
45    ## FIXME: should not be so hard to implement; see
46    ##      moddet_ge_real() in ../../../modules/lapack/Lapack.c
47    ## the 'sign' would have to be complex z, with |z|=1
48    .Internal(det_ge_real(x, logarithm))
49}
50