depmaker
[tridge/junkcode.git] / modf.c
1 #include <stdio.h>
2 #include <math.h>
3
4 /* a replacement for modf that doesn't need the math library. Should
5    be portable, but slow */
6 static double my_modf(double x0, double *iptr)
7 {
8         int i;
9         long l;
10         double x = x0;
11         double f = 1.0;
12
13         for (i=0;i<100;i++) {
14                 l = (long)x;
15                 if (l <= (x+1) && l >= (x-1)) break;
16                 x *= 0.1;
17                 f *= 10.0;
18         }
19
20         if (i == 100) {
21                 /* yikes! the number is beyond what we can handle. What do we do? */
22                 (*iptr) = 0;
23                 return 0;
24         }
25
26         if (i != 0) {
27                 double i2;
28                 double ret;
29
30                 ret = my_modf(x0-l*f, &i2);
31                 (*iptr) = l*f + i2;
32                 return ret;
33         } 
34
35         (*iptr) = l;
36         return x - (*iptr);
37 }
38
39 static void test1(double x)
40 {
41         double i1, i2;
42         double d1, d2;
43         d1 = modf(x, &i1);
44         d2 = my_modf(x, &i2);
45         if (d1 != d2 || i1 != i2) {
46                 printf("%f\t%f\n", d1, i1);
47                 printf("%f\t%f\n", d2, i2);
48         }
49 }
50
51 int main()
52 {
53         test1(1.9);
54         test1(164976598.8749875);
55         test1(16497659895798297498763943987984.8749875);
56         test1(-8734987047074075050509709874000789.1749875);
57         test1(-16497659895798297498763943987984.8749875);
58         test1(8734903083084098487047074075050509709874000789.1749875);
59         return 0;
60 }