From f9c64426d74493063af2b9367a0da728e74bb315 Mon Sep 17 00:00:00 2001 From: NunoSempere Date: Sat, 22 Jul 2023 19:36:43 +0200 Subject: [PATCH] add mean and std for arrays. --- README.md | 5 +++-- squiggle.c | 21 ++++++++++++++++++--- squiggle.h | 2 ++ 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 217bc55..2610ea2 100644 --- a/README.md +++ b/README.md @@ -77,9 +77,8 @@ Behaviour on error can be toggled by the `EXIT_ON_ERROR` variable. This library ## To do list -- [ ] Rename functions to something more self-explanatory, e.g,. sample_sample_sample_unit_normal. - [ ] Have some more complicated & realistic example -- [ ] Add summarization functions, like mean, std, 90% ci (or all c.i.?) +- [ ] Add summarization functions: 90% ci (or all c.i.?) - [ ] Publish online - [ ] Support all distribution functions in - [ ] Support all distribution functions in , and do so efficiently @@ -105,3 +104,5 @@ Behaviour on error can be toggled by the `EXIT_ON_ERROR` variable. This library - [x] Explain nested functions - [x] Explain exit on error - [x] Explain individual examples +- [x] Rename functions to something more self-explanatory, e.g,. `sample_unit_normal`. +- [x] Add summarization functions: mean, std diff --git a/squiggle.c b/squiggle.c index 377341f..11b66f8 100644 --- a/squiggle.c +++ b/squiggle.c @@ -76,11 +76,11 @@ float sample_to(float low, float high, uint32_t* seed) // Array helpers float array_sum(float* array, int length) { - float output = 0.0; + float sum = 0.0; for (int i = 0; i < length; i++) { - output += array[i]; + sum += array[i]; } - return output; + return sum; } void array_cumsum(float* array_to_sum, float* array_cumsummed, int length) @@ -91,6 +91,21 @@ void array_cumsum(float* array_to_sum, float* array_cumsummed, int length) } } +float array_mean(float* array, int length){ + float sum = array_sum(array, length); + return sum / length; +} + +float array_std(float* array, int length){ + float mean = array_mean(array, length); + float std = 0.0; + for (int i = 0; i < length; i++) { + std += pow(array[i] - mean, 2.0); + } + std=sqrt(std/length); + return std; +} + // Mixture function float sample_mixture(float (*samplers[])(uint32_t*), float* weights, int n_dists, uint32_t* seed) { diff --git a/squiggle.h b/squiggle.h index 21c6231..84d95eb 100644 --- a/squiggle.h +++ b/squiggle.h @@ -20,6 +20,8 @@ float sample_to(float low, float high, uint32_t* seed); // Array helpers float array_sum(float* array, int length); void array_cumsum(float* array_to_sum, float* array_cumsummed, int length); +float array_mean(float* array, int length); +float array_std(float* array, int length); // Mixture function float sample_mixture(float (*samplers[])(uint32_t*), float* weights, int n_dists, uint32_t* seed);