Skip to content

Commit

Permalink
math: add ceil function
Browse files Browse the repository at this point in the history
  • Loading branch information
Viviane Potocnik committed Oct 20, 2023
1 parent c076862 commit 22421ab
Show file tree
Hide file tree
Showing 3 changed files with 92 additions and 0 deletions.
31 changes: 31 additions & 0 deletions sw/math/src/math/ceil.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#include "libm.h"

#if FLT_EVAL_METHOD==0 || FLT_EVAL_METHOD==1
#define EPS DBL_EPSILON
#elif FLT_EVAL_METHOD==2
#define EPS LDBL_EPSILON
#endif
static const double_t toint = 1/EPS;

double ceil(double x)
{
union {double f; uint64_t i;} u = {x};
int e = u.i >> 52 & 0x7ff;
double_t y;

if (e >= 0x3ff+52 || x == 0)
return x;
/* y = int(x) - x, where int(x) is an integer neighbor of x */
if (u.i >> 63)
y = x - toint + toint - x;
else
y = x + toint - toint - x;
/* special case because of non-nearest rounding modes */
if (e <= 0x3ff-1) {
FORCE_EVAL(y);
return u.i >> 63 ? -0.0 : 1;
}
if (y < 0)
return x + y + 1;
return x + y;
}
27 changes: 27 additions & 0 deletions sw/math/src/math/ceilf.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#include "libm.h"

float ceilf(float x)
{
union {float f; uint32_t i;} u = {x};
int e = (int)(u.i >> 23 & 0xff) - 0x7f;
uint32_t m;

if (e >= 23)
return x;
if (e >= 0) {
m = 0x007fffff >> e;
if ((u.i & m) == 0)
return x;
FORCE_EVAL(x + 0x1p120f);
if (u.i >> 31 == 0)
u.i += m;
u.i &= ~m;
} else {
FORCE_EVAL(x + 0x1p120f);
if (u.i >> 31)
u.f = -0.0;
else if (u.i << 1)
u.f = 1.0;
}
return u.f;
}
34 changes: 34 additions & 0 deletions sw/math/src/math/ceill.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#include "libm.h"

#if LDBL_MANT_DIG == 53 && LDBL_MAX_EXP == 1024
long double ceill(long double x)
{
return ceil(x);
}
#elif (LDBL_MANT_DIG == 64 || LDBL_MANT_DIG == 113) && LDBL_MAX_EXP == 16384

static const long double toint = 1/LDBL_EPSILON;

long double ceill(long double x)
{
union ldshape u = {x};
int e = u.i.se & 0x7fff;
long double y;

if (e >= 0x3fff+LDBL_MANT_DIG-1 || x == 0)
return x;
/* y = int(x) - x, where int(x) is an integer neighbor of x */
if (u.i.se >> 15)
y = x - toint + toint - x;
else
y = x + toint - toint - x;
/* special case because of non-nearest rounding modes */
if (e <= 0x3fff-1) {
FORCE_EVAL(y);
return u.i.se >> 15 ? -0.0 : 1;
}
if (y < 0)
return x + y + 1;
return x + y;
}
#endif

0 comments on commit 22421ab

Please sign in to comment.