summaryrefslogtreecommitdiff
path: root/libm/double/noncephes.c
blob: 72f129d550187a6371dcdecb9abd45f79fcfe2c2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/*
 * This file contains math functions missing from the Cephes library.
 *
 * May 22, 2001         Manuel Novoa III
 *
 *    Added modf and fmod.
 *
 * TODO:
 *    Break out functions into seperate object files as is done
 *       by (for example) stdio.  Also do this with cephes files.
 */

#include <math.h>
#include <errno.h>

#undef UNK

/* Set this to nonzero to enable a couple of shortcut tests in fmod. */
#define SPEED_OVER_SIZE 0

/**********************************************************************/

double modf(double x, double *iptr)
{
	double y;

#ifdef UNK
	mtherr( "modf", DOMAIN );
	*iptr = NAN;
	return NAN;
#endif

#ifdef NANS
	if( isnan(x) ) {
		*iptr = x;
		return x;
	}
#endif

#ifdef INFINITIES
	if(!isfinite(x)) {
		*iptr = x;				/* Matches glibc, but returning NAN */
		return 0;				/* makes more sense to me... */
	}
#endif

	if (x < 0) {				/* Round towards 0. */
		y = ceil(x);
	} else {
		y = floor(x);
	}

	*iptr = y;
	return x - y;
}

/**********************************************************************/

extern double NAN;

double fmod(double x, double y)
{
	double z;
	int negative, ex, ey;

#ifdef UNK
	mtherr( "fmod", DOMAIN );
	return NAN;
#endif

#ifdef NANS
	if( isnan(x) || isnan(y) ) {
		errno = EDOM;
		return NAN; 
	}
#endif

	if (y == 0) {
		errno = EDOM;
		return NAN; 
	}

#ifdef INFINITIES
	if(!isfinite(x)) {
		errno = EDOM;
		return NAN;
	}

#if SPEED_OVER_SIZE
	if(!isfinite(y)) {
		return x;
	}
#endif
#endif

#if SPEED_OVER_SIZE
	if (x == 0) {
		return 0;
	}
#endif

	negative = 0;
	if (x < 0) {
		negative = 1;
		x = -x;
	}

	if (y < 0) {
		y = -y;
	}

	frexp(y,&ey);
	while (x >= y) {
		frexp(x,&ex);
		z = ldexp(y,ex-ey);
		if (z > x) {
			z /= 2;
		}
		x -= z;
	}

	if (negative) {
		return -x;
	} else {
		return x;
	}
}