3266
|
1 ## Copyright (C) 1995, 1996 Kurt Hornik |
3426
|
2 ## |
3922
|
3 ## This file is part of Octave. |
|
4 ## |
|
5 ## Octave is free software; you can redistribute it and/or modify it |
|
6 ## under the terms of the GNU General Public License as published by |
2537
|
7 ## the Free Software Foundation; either version 2, or (at your option) |
|
8 ## any later version. |
3426
|
9 ## |
3922
|
10 ## Octave is distributed in the hope that it will be useful, but |
2537
|
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of |
|
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
3426
|
13 ## General Public License for more details. |
|
14 ## |
2537
|
15 ## You should have received a copy of the GNU General Public License |
3922
|
16 ## along with Octave; see the file COPYING. If not, write to the Free |
5307
|
17 ## Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA |
|
18 ## 02110-1301, USA. |
2537
|
19 |
3321
|
20 ## -*- texinfo -*- |
|
21 ## @deftypefn {Mapping Function} {} erfinv (@var{z}) |
3599
|
22 ## Computes the inverse of the error function. |
5642
|
23 ## @seealso{erf, erfc} |
3321
|
24 ## @end deftypefn |
2537
|
25 |
5428
|
26 ## Author: KH <Kurt.Hornik@wu-wien.ac.at> |
2537
|
27 ## Created: 27 September 1994 |
|
28 ## Adapted-By: jwe |
|
29 |
3266
|
30 function [y, iterations] = erfinv (x) |
3426
|
31 |
2537
|
32 if (nargin != 1) |
6046
|
33 print_usage (); |
2537
|
34 endif |
3266
|
35 |
|
36 maxit = 100; |
|
37 tol = eps; |
|
38 |
|
39 iterations = 0; |
|
40 |
4844
|
41 sz = size (x); |
|
42 nel = numel (x); |
|
43 |
|
44 x = reshape (x, nel, 1); |
|
45 y = zeros (nel, 1); |
3266
|
46 |
4077
|
47 i = find ((x < -1) | (x > 1) | isnan(x)); |
2537
|
48 if any (i) |
|
49 y(i) = NaN * ones (length (i), 1); |
|
50 endif |
|
51 |
2621
|
52 t = find (x == -1); |
2663
|
53 y (t) = (-Inf) * ones (size (t)); |
2621
|
54 |
|
55 t = find (x == 1); |
|
56 y (t) = Inf * ones (size (t)); |
3266
|
57 |
2537
|
58 i = find ((x > -1) & (x < 1)); |
|
59 if any (i) |
2968
|
60 s = sqrt (pi) / 2; |
2537
|
61 z_old = ones (length (i), 1); |
3266
|
62 z_new = sqrt (-log (1 - abs (x(i)))) .* sign (x(i)); |
3599
|
63 while (any (abs (erf (z_new) - x(i)) > tol * abs (x(i)))) |
2537
|
64 z_old = z_new; |
2813
|
65 z_new = z_old - (erf (z_old) - x(i)) .* exp (z_old.^2) * s; |
3266
|
66 if (++iterations > maxit) |
3426
|
67 warning ("erfinv: iteration limit exceeded"); |
|
68 break; |
3266
|
69 endif |
2537
|
70 endwhile |
|
71 y(i) = z_new; |
|
72 endif |
3426
|
73 |
4844
|
74 y = reshape (y, sz); |
3426
|
75 |
2537
|
76 endfunction |