Quantum/lib/math.c
2023-12-16 16:17:02 +01:00

44 lines
777 B
C

#include "libwasm.h"
#define EULER 2.7182818284
#define EPS 1.0e-9
double exp(const double a) {
if (a < 0.0) return 1.0 / exp (-a);
int ip = a;
const double dp = a - ip;
double result = 1.0, m = dp, f = 1.0, s = 1.0;
for (;;) {
const double e = m / f;
result += e;
if (e < EPS) break;
m *= dp;
s += 1.0;
f *= s;
}
m = EULER;
for (;;) {
const int n = ip & 1;
if (n) result *= m;
ip >>= 1;
if (!ip) break;
m *= m;
}
return result;
}
double fabs (const double a) {
if (a < 0.0) return -a;
return a;
}
double sqrt(const double a) {
if (a <= 0.0) return 0;
double x = a;
double root;
while (1) {
root = 0.5 * (x + (a / x));
if (fabs(root - x) < EPS) break;
x = root;
}
return root;
}