10203
|
1 ## Copyright (C) 2010 John W. Eaton |
|
2 ## |
|
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 |
|
7 ## the Free Software Foundation; either version 3 of the License, or (at |
|
8 ## your option) any later version. |
|
9 ## |
|
10 ## Octave is distributed in the hope that it will be useful, but |
|
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of |
|
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
|
13 ## General Public License for more details. |
|
14 ## |
|
15 ## You should have received a copy of the GNU General Public License |
|
16 ## along with Octave; see the file COPYING. If not, see |
|
17 ## <http://www.gnu.org/licenses/>. |
|
18 |
|
19 ## -*- texinfo -*- |
|
20 ## @deftypefn {Function File} chop (@var{x}, @var{d}, @var{u}) |
|
21 ## Truncate elements of @var{x} to @var{d} digits such that the |
|
22 ## resulting digits are exactly divisible by @var{u}. If @var{u} is not |
|
23 ## specified it defaults to 10. |
|
24 ## |
|
25 ## @example |
|
26 ## @group |
|
27 ## chop (-pi, 5, 10) |
|
28 ## @result{} -3.14200000000000 |
|
29 ## chop (-pi, 5, 5) |
|
30 ## @result{} -3.14150000000000 |
|
31 ## @end group |
|
32 ## @end example |
|
33 ## @end deftypefn |
|
34 |
|
35 function retval = chop (x, digits, units = 10) |
|
36 |
|
37 if (nargin == 2 || nargin == 3) |
|
38 tmp = abs (x); |
|
39 |
|
40 ## Avoid computing log (0). |
|
41 tmp(x == 0) = 1; |
|
42 |
|
43 ## Digits to the left of the decimal. |
|
44 tmp = floor (log10 (tmp) + 1); |
|
45 |
|
46 ## The expression |
|
47 ## |
|
48 ## round (x .* inflate) |
|
49 ## |
|
50 ## produces an integer that contains the digits we want to keep. |
|
51 ## Multiplying by deflate puts the decimal back where it belngs. |
|
52 ## |
|
53 ## Further scaling and rounding with the units factor produces a |
|
54 ## value with digits exactly divisible by units. We skip that step |
|
55 ## unless units was explicitly provided. |
|
56 |
|
57 inflate = 10 .^ (digits - tmp); |
|
58 deflate = 10 .^ (tmp - digits); |
|
59 if (nargin == 2) |
|
60 retval = deflate .* round (x .* inflate); |
|
61 else |
|
62 retval = units .* deflate .* round (round (x .* inflate) ./ units); |
|
63 endif |
|
64 else |
|
65 print_usage (); |
|
66 endif |
|
67 |
|
68 endfunction |
|
69 |
|
70 %!assert (chop (e, 3), 2.72) |
|
71 %!assert (chop (e, 4), 2.718) |
|
72 %!assert (chop (e, 4, 5), 2.72) |
|
73 %!assert (chop (e, 4, 7), 2.716) |
|
74 %!assert (chop (-e, 3), -2.72) |
|
75 %!assert (chop (-e, 4), -2.718) |
|
76 %!assert (chop (-e, 4, 5), -2.72) |
|
77 %!assert (chop (-e, 4, 7), -2.716) |
|
78 %!assert (chop (hilb (3), 3), [1,.5,.333;.5,.333,.25;.333,.25,.2]) |
|
79 %!assert (chop (hilb (3), 2, 7), [.7,.49,.35;.49,.35,.28;.35,.28,.21], 2*eps) |