1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 2004, 2015 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
22 #include "chart-geometry.h"
26 static const double standard_tick[] = {1, 2, 5, 10};
28 /* Adjust tick to be a sensible value
29 ie: ... 0.1,0.2,0.5, 1,2,5, 10,20,50 ... */
31 chart_rounded_tick (double tick, struct decimal *result)
35 struct decimal ddif = {1, 1000};
37 /* Avoid arithmetic problems with very small values */
38 if (fabs (tick) < DBL_EPSILON)
46 decimal_from_double (&dt, tick);
48 double expd = dec_log10 (&dt) - 1;
50 for (i = 0 ; i < 4 ; ++i)
52 struct decimal candidate;
55 decimal_init (&candidate, standard_tick[i], expd);
58 decimal_subtract (&delta, &candidate);
59 delta.ordinate = llabs (delta.ordinate);
61 if (decimal_cmp (&delta, &ddif) < 0)
70 Find a set {LOWER, INTERVAL, N_TICKS} such that:
73 LOWER + INTERVAL > LOWDBL,
75 LOWER + N_TICKS * INTERVAL < HIGHDBL
76 LOWER + (N_TICKS + 1) * INTERVAL >= HIGHDBL
80 and X is an element of {1, 2, 5}
86 |....+....+....+. .+....|
91 chart_get_scale (double highdbl, double lowdbl,
92 struct decimal *lower,
93 struct decimal *interval,
97 double fitness = DBL_MAX;
102 assert (highdbl >= lowdbl);
104 decimal_from_double (&high, highdbl);
105 decimal_from_double (&low, lowdbl);
107 struct decimal diff = high;
108 decimal_subtract (&diff, &low);
110 double expd = dec_log10 (&diff) - 2;
112 /* Find the most pleasing interval */
113 for (i = 1; i < 4; ++i)
115 struct decimal clbound = low;
116 struct decimal cubound = high;
117 struct decimal candidate;
118 decimal_init (&candidate, standard_tick[i], expd);
120 decimal_divide (&clbound, &candidate);
121 int fl = decimal_floor (&clbound);
122 decimal_int_multiply (&candidate, fl);
126 decimal_init (&candidate, standard_tick[i], expd);
127 decimal_divide (&cubound, &candidate);
128 int fu = decimal_ceil (&cubound);
129 decimal_int_multiply (&candidate, fu);
133 decimal_init (&candidate, standard_tick[i], expd);
134 decimal_subtract (&cubound, &clbound);
135 decimal_divide (&cubound, &candidate);
138 ord_t n_int = decimal_floor (&cubound);
140 /* We prefer to have between 5 and 10 tick marks on a scale */
141 double f = 1 - exp (-0.2 * fabs (n_int - 7.5) / 7.5);
147 *interval = candidate;