Keisuke Sehara / Mbed 2 deprecated STM32_Whisking

Dependencies:   mbed

random.cpp

Committer:
gwappa
Date:
2018-05-14
Revision:
0:f736749c33d2
Child:
2:0c241937eabd

File content as of revision 0:f736749c33d2:

#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);
        }
    }
}