From a845c628e34e22633b63d383182b07348d4cc8b2 Mon Sep 17 00:00:00 2001 From: milner Date: Tue, 28 Jun 2022 01:49:34 +0000 Subject: [PATCH] feat(examples): extend hello with a second translation unit and a test Gives the archive more than one member and gives meowc test something to run. --- examples/hello/build.meow | 6 ++++++ examples/hello/src/mathx/stats.c | 17 +++++++++++++++++ examples/hello/tests/mathx_test.c | 28 ++++++++++++++++++++++++++++ 3 files changed, 51 insertions(+) create mode 100644 examples/hello/src/mathx/stats.c create mode 100644 examples/hello/tests/mathx_test.c diff --git a/examples/hello/build.meow b/examples/hello/build.meow index f221367..08befa7 100644 --- a/examples/hello/build.meow +++ b/examples/hello/build.meow @@ -17,3 +17,9 @@ bin hello { use mathx define GREETING="meow" } + +test mathx_test { + srcs tests/*.c + include include + use mathx +} diff --git a/examples/hello/src/mathx/stats.c b/examples/hello/src/mathx/stats.c new file mode 100644 index 0000000..67cf80d --- /dev/null +++ b/examples/hello/src/mathx/stats.c @@ -0,0 +1,17 @@ +#include "mathx.h" +#include + +double stats_mean(const double *a, size_t n) { + if (n == 0) return 0.0; + double sum = 0.0; + for (size_t i = 0; i < n; i++) sum += a[i]; + return sum / (double)n; +} + +double stats_stddev(const double *a, size_t n) { + if (n < 2) return 0.0; + double m = stats_mean(a, n); + double acc = 0.0; + for (size_t i = 0; i < n; i++) acc += (a[i] - m) * (a[i] - m); + return sqrt(acc / (double)(n - 1)); +} diff --git a/examples/hello/tests/mathx_test.c b/examples/hello/tests/mathx_test.c new file mode 100644 index 0000000..fd74232 --- /dev/null +++ b/examples/hello/tests/mathx_test.c @@ -0,0 +1,28 @@ +#include "mathx.h" +#include +#include + +static int failures = 0; + +static void check(const char *what, double got, double want) { + if (fabs(got - want) > 1e-9) { + printf(" %s: got %.12f, want %.12f\n", what, got, want); + failures++; + } +} + +int main(void) { + const double a[] = {1.0, 2.0, 3.0, 4.0}; + const double b[] = {4.0, 3.0, 2.0, 1.0}; + const double unit[] = {3.0, 4.0}; + + check("vec_dot", vec_dot(a, b, 4), 20.0); + check("vec_sum", vec_sum(a, 4), 10.0); + check("vec_norm", vec_norm(unit, 2), 5.0); + check("stats_mean", stats_mean(a, 4), 2.5); + check("stats_stddev", stats_stddev(a, 4), sqrt(5.0 / 3.0)); + check("stats_mean empty", stats_mean(a, 0), 0.0); + check("stats_stddev single", stats_stddev(a, 1), 0.0); + + return failures == 0 ? 0 : 1; +}