6 * adapted from Paul Heckbert's algorithm on p 657-659 of
7 * Andrew S. Glassner's book, "Graphics Gems"
12 #include "tickmarks.h"
14 #define MAX(a, b) (((a) < (b)) ? (b) : (a))
16 static double nicenum(double x, int round)
18 int exp; /* exponent of x */
19 double f; /* fractional part of x */
21 exp = floor(log10(x));
22 f = x / pow(10.0, exp);
25 return 1.0 * pow(10.0, exp);
27 return 2.0 * pow(10.0, exp);
29 return 5.0 * pow(10.0, exp);
30 return 10.0 * pow(10.0, exp);
33 return 1.0 * pow(10.0, exp);
35 return 2.0 * pow(10.0, exp);
37 return 5.0 * pow(10.0, exp);
38 return 10.0 * pow(10.0, exp);
41 int calc_tickmarks(double min, double max, int nticks, struct tickmark **tm)
45 double d; /* tick mark spacing */
46 double graphmin, graphmax; /* graph range min and max */
50 /* we expect min != max */
51 range = nicenum(max - min, 0);
52 d = nicenum(range / (nticks - 1), 1);
53 graphmin = floor(min / d) * d;
54 graphmax = ceil(max / d) * d;
55 nfrac = MAX(-floor(log10(d)), 0);
56 snprintf(str, sizeof(str)-1, "%%.%df", nfrac);
58 count = ((graphmax + 0.5 * d) - graphmin) / d + 1;
59 *tm = malloc(sizeof(**tm) * count);
62 for (x = graphmin; x < graphmax + 0.5 * d; x += d) {
64 sprintf((*tm)[i].string, str, x);
72 static void test_range(double x, double y)
76 struct tickmark *tm = NULL;
77 printf("Testing range %g - %g\n", x, y);
78 nticks = calc_tickmarks(x, y, 10, &tm);
80 for (i = 0; i < nticks; i++) {
81 printf(" (%s) %g\n", tm[i].string, tm[i].value);
87 int main(int argc, char *argv[])
89 test_range(0.0005, 0.008);
92 test_range(50.5, 80.8);
93 test_range(-20, 20.8);
94 test_range(-30, 700.8);