xref: /haiku/src/system/libroot/posix/musl/math/roundf.c (revision f504f61099b010fbfa94b1cc63d2e9072c7f7185)
1*f504f610SAugustin Cavalier #include "libm.h"
2*f504f610SAugustin Cavalier 
3*f504f610SAugustin Cavalier #if FLT_EVAL_METHOD==0
4*f504f610SAugustin Cavalier #define EPS FLT_EPSILON
5*f504f610SAugustin Cavalier #elif FLT_EVAL_METHOD==1
6*f504f610SAugustin Cavalier #define EPS DBL_EPSILON
7*f504f610SAugustin Cavalier #elif FLT_EVAL_METHOD==2
8*f504f610SAugustin Cavalier #define EPS LDBL_EPSILON
9*f504f610SAugustin Cavalier #endif
10*f504f610SAugustin Cavalier static const float_t toint = 1/EPS;
11*f504f610SAugustin Cavalier 
roundf(float x)12*f504f610SAugustin Cavalier float roundf(float x)
13*f504f610SAugustin Cavalier {
14*f504f610SAugustin Cavalier 	union {float f; uint32_t i;} u = {x};
15*f504f610SAugustin Cavalier 	int e = u.i >> 23 & 0xff;
16*f504f610SAugustin Cavalier 	float_t y;
17*f504f610SAugustin Cavalier 
18*f504f610SAugustin Cavalier 	if (e >= 0x7f+23)
19*f504f610SAugustin Cavalier 		return x;
20*f504f610SAugustin Cavalier 	if (u.i >> 31)
21*f504f610SAugustin Cavalier 		x = -x;
22*f504f610SAugustin Cavalier 	if (e < 0x7f-1) {
23*f504f610SAugustin Cavalier 		FORCE_EVAL(x + toint);
24*f504f610SAugustin Cavalier 		return 0*u.f;
25*f504f610SAugustin Cavalier 	}
26*f504f610SAugustin Cavalier 	y = x + toint - toint - x;
27*f504f610SAugustin Cavalier 	if (y > 0.5f)
28*f504f610SAugustin Cavalier 		y = y + x - 1;
29*f504f610SAugustin Cavalier 	else if (y <= -0.5f)
30*f504f610SAugustin Cavalier 		y = y + x + 1;
31*f504f610SAugustin Cavalier 	else
32*f504f610SAugustin Cavalier 		y = y + x;
33*f504f610SAugustin Cavalier 	if (u.i >> 31)
34*f504f610SAugustin Cavalier 		y = -y;
35*f504f610SAugustin Cavalier 	return y;
36*f504f610SAugustin Cavalier }
37