Keisuke Sehara
/
STM32_Whisking
fast-feedback virtual target task code on STM Nucleo
Diff: random.cpp
- Revision:
- 0:f736749c33d2
- Child:
- 2:0c241937eabd
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/random.cpp Mon May 14 14:12:32 2018 +0000 @@ -0,0 +1,29 @@ +#include "random.h" +#include "mbed.h" +#include <limits.h> + +namespace random +{ + AnalogIn noise(RANDOM_NOISE_PIN); + + void init() { + srand(noise.read_u16()); + } + + uint16_t exponential(const uint16_t& tau_ms, const uint16_t& cutoff, const unsigned int& resolution){ + double ftau = (double)tau_ms; + double fcutoff = (double)cutoff; + double cumulativeFraction = ((double)(rand() & resolution))/resolution; + + // calculate the point (in exponential distribution) from the inverse of its cumulative density function + double point = -ftau * log(1-cumulativeFraction); + + // return as uint16 value. + // if `point` is unreasonably long, then return `cutoff` instead. + if (point > fcutoff) { + return cutoff; + } else { + return (uint16_t)(point+0.5); + } + } +}