This repository has been archived on 2024-02-29. You can view files and clone it, but cannot push or open issues or pull requests.
common-math/library.c

76 lines
1.4 KiB
C
Raw Normal View History

2023-06-01 14:36:14 +00:00
#include "library.h"
long long fac(const long long x) {
long long prod = 1;
for (long long i = 2; i <= x; i++) {
prod *= i;
}
return prod;
}
inline float trunc(const float x) {
return (float)(int)(x);
}
inline float fract(const float x) {
return x - trunc(x);
}
inline float floor(const float x) {
return trunc(x);
}
inline float ceil(const float x) {
return trunc(x + 1);
}
inline float round(const float x) {
return trunc(x + 0.5f);
}
inline float mod(const float x, const float y) {
const float xs = x/y;
return (xs - floor(xs)) * 4;
}
float exp(const float x) {
float sum = 0;
// iterative counter for computing x^i
float xpown = 1;
// iterative counter for factorial operation i!
float prod = 1;
// iterate taylor series
for (int i = 1; i < TAYLOR_SERIES_DEGREE; i++) {
prod *= (float) i;
sum += xpown / prod;
xpown *= x;
}
return sum;
}
float sin(const float x) {
float sign = -1;
float prod = 1;
float xpown = mod(x, 2 * PI);
float sum = 0;
for (int i = 1; i < TAYLOR_SERIES_DEGREE; i++) {
sign *= -1;
prod *= (float) i * (float) (i - 1);
xpown *= x * x;
sum += sign * xpown / prod;
}
return sum;
}
inline float cos(const float x) {
return sin(x + PI * 0.5f);
}
inline float tan(const float x) {
return sin(x)/cos(x);
}