fast-feedback virtual target task code on STM Nucleo

Dependencies:   mbed

Committer:
gwappa
Date:
Thu Dec 13 07:18:43 2018 +0000
Revision:
32:1416e015016c
Parent:
26:b4421d1ee57a
change to use the Staged state

Who changed what in which revision?

UserRevisionLine numberNew contents of line
gwappa 0:f736749c33d2 1 #include "random.h"
gwappa 0:f736749c33d2 2 #include "mbed.h"
gwappa 0:f736749c33d2 3 #include <limits.h>
gwappa 0:f736749c33d2 4
gwappa 0:f736749c33d2 5 namespace random
gwappa 0:f736749c33d2 6 {
gwappa 0:f736749c33d2 7 AnalogIn noise(RANDOM_NOISE_PIN);
gwappa 2:0c241937eabd 8 bool initialized = false;
gwappa 0:f736749c33d2 9
gwappa 0:f736749c33d2 10 void init() {
gwappa 13:8ea85a33e37a 11 srand(((uint32_t)noise.read_u16())<<16 & ((uint32_t)noise.read_u16()));
gwappa 2:0c241937eabd 12 initialized = true;
gwappa 2:0c241937eabd 13 }
gwappa 2:0c241937eabd 14
gwappa 13:8ea85a33e37a 15 uint32_t unif(const uint32_t& nlevels) {
gwappa 2:0c241937eabd 16 if (!initialized) {
gwappa 2:0c241937eabd 17 init();
gwappa 2:0c241937eabd 18 }
gwappa 13:8ea85a33e37a 19 return ((uint32_t)rand()) % nlevels;
gwappa 0:f736749c33d2 20 }
gwappa 0:f736749c33d2 21
gwappa 13:8ea85a33e37a 22 uint32_t exponential(const uint32_t& tau, const uint32_t& cutoff, const unsigned int& resolution){
gwappa 2:0c241937eabd 23 if (!initialized) {
gwappa 2:0c241937eabd 24 init();
gwappa 2:0c241937eabd 25 }
gwappa 2:0c241937eabd 26
gwappa 13:8ea85a33e37a 27 double ftau = (double)tau;
gwappa 0:f736749c33d2 28 double fcutoff = (double)cutoff;
gwappa 0:f736749c33d2 29 double cumulativeFraction = ((double)(rand() & resolution))/resolution;
gwappa 0:f736749c33d2 30
gwappa 0:f736749c33d2 31 // calculate the point (in exponential distribution) from the inverse of its cumulative density function
gwappa 0:f736749c33d2 32 double point = -ftau * log(1-cumulativeFraction);
gwappa 0:f736749c33d2 33
gwappa 13:8ea85a33e37a 34 // return as uint32 value.
gwappa 0:f736749c33d2 35 // if `point` is unreasonably long, then return `cutoff` instead.
gwappa 0:f736749c33d2 36 if (point > fcutoff) {
gwappa 0:f736749c33d2 37 return cutoff;
gwappa 0:f736749c33d2 38 } else {
gwappa 13:8ea85a33e37a 39 return (uint32_t)(point+0.5);
gwappa 0:f736749c33d2 40 }
gwappa 0:f736749c33d2 41 }
gwappa 0:f736749c33d2 42 }