Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add fmin/fmax functions to math.h #303

Merged
merged 7 commits into from
Feb 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions mos-platform/common/c/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ add_platform_library(common-c
# inttypes.h
inttypes.c

# math.h
math.cc

# setjmp.h
setjmp.S

Expand Down
20 changes: 20 additions & 0 deletions mos-platform/common/c/math.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#include <math.h>

template <typename T> static inline T _fmax(const T x, const T y) {
if (isnan(y)) return x;
// if x is nan, then x > y is false, so the ternary returns y
return x > y ? x : y;
}

template <typename T> static inline T _fmin(const T x, const T y) {
if (isnan(y)) return x;
// if x is nan, then x < y is false, so the ternary returns y
return x < y ? x : y;
}

extern "C" {
double fmin(double x, double y) { return _fmin<double>(x, y); }
double fmax(double x, double y) { return _fmax<double>(x, y); }
float fminf(float x, float y) { return _fmin<float>(x, y); }
float fmaxf(float x, float y) { return _fmax<float>(x, y); }
}
7 changes: 7 additions & 0 deletions mos-platform/common/include/math.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@ extern "C" {

#define INFINITY (1.0f / 0.0f)

#define isnan(arg) __builtin_isnan(arg)

double fmin(double x, double y);
double fmax(double x, double y);
float fminf(float x, float y);
float fmaxf(float x, float y);

#ifdef __cplusplus
}
#endif
Expand Down