1 ## Copyright (C) 2012 Rik Wehbring
2 ## Copyright (C) 1995-2012 Kurt Hornik
4 ## This file is part of Octave.
6 ## Octave is free software; you can redistribute it and/or modify it
7 ## under the terms of the GNU General Public License as published by
8 ## the Free Software Foundation; either version 3 of the License, or (at
9 ## your option) any later version.
11 ## Octave is distributed in the hope that it will be useful, but
12 ## WITHOUT ANY WARRANTY; without even the implied warranty of
13 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 ## General Public License for more details.
16 ## You should have received a copy of the GNU General Public License
17 ## along with Octave; see the file COPYING. If not, see
18 ## <http://www.gnu.org/licenses/>.
21 ## @deftypefn {Function File} {} tinv (@var{x}, @var{n})
22 ## For each element of @var{x}, compute the quantile (the inverse of
23 ## the CDF) at @var{x} of the t (Student) distribution with @var{n}
24 ## degrees of freedom. This function is analogous to looking in a table
25 ## for the t-value of a single-tailed distribution.
28 ## For very large n, the "correct" formula does not really work well,
29 ## and the quantiles of the standard normal distribution are used
32 ## Author: KH <Kurt.Hornik@wu-wien.ac.at>
33 ## Description: Quantile function of the t distribution
35 function inv = tinv (x, n)
42 [retval, x, n] = common_size (x, n);
44 error ("tinv: X and N must be of common size or scalars");
48 if (iscomplex (x) || iscomplex (n))
49 error ("tinv: X and N must not be complex");
52 if (isa (x, "single") || isa (n, "single"))
53 inv = NaN (size (x), "single");
58 k = (x == 0) & (n > 0);
61 k = (x == 1) & (n > 0);
65 k = (x > 0) & (x < 1);
66 if ((n > 0) && (n < 10000))
67 inv(k) = (sign (x(k) - 1/2)
68 .* sqrt (n * (1 ./ betainv (2*min (x(k), 1 - x(k)),
71 ## For large n, use the quantiles of the standard normal
72 inv(k) = stdnormal_inv (x(k));
75 k = (x > 0) & (x < 1) & (n > 0) & (n < 10000);
76 inv(k) = (sign (x(k) - 1/2)
77 .* sqrt (n(k) .* (1 ./ betainv (2*min (x(k), 1 - x(k)),
80 ## For large n, use the quantiles of the standard normal
81 k = (x > 0) & (x < 1) & (n >= 10000);
82 inv(k) = stdnormal_inv (x(k));
89 %! x = [-1 0 0.5 1 2];
90 %!assert(tinv (x, ones(1,5)), [NaN -Inf 0 Inf NaN]);
91 %!assert(tinv (x, 1), [NaN -Inf 0 Inf NaN], eps);
92 %!assert(tinv (x, [1 0 NaN 1 1]), [NaN NaN NaN Inf NaN], eps);
93 %!assert(tinv ([x(1:2) NaN x(4:5)], 1), [NaN -Inf NaN Inf NaN]);
95 %% Test class of input preserved
96 %!assert(tinv ([x, NaN], 1), [NaN -Inf 0 Inf NaN NaN], eps);
97 %!assert(tinv (single([x, NaN]), 1), single([NaN -Inf 0 Inf NaN NaN]), eps("single"));
98 %!assert(tinv ([x, NaN], single(1)), single([NaN -Inf 0 Inf NaN NaN]), eps("single"));
100 %% Test input validation
104 %!error tinv (ones(3),ones(2))
105 %!error tinv (ones(2),ones(3))