Would Poisson Distribution code in C work in Arduino IDE?

I saw this code at this site.

This code is in C.

#include <math.h>
#include <stdlib.h>

float nextTime(float rateParameter)
{
    return -logf(1.0f - (float) random() / (RAND_MAX + 1)) / rateParameter;
}

If I remove "#include <stdlib.h>", would this work in the Arduino IDE? Do you have any ideas to test this?

Pretty much any c code will work, provided all necessary libraries and other "support" code is available or can be ported. Arduino uses plain old industry-standard ANI/ISO c/c++.

Regards,
Ray L.

Do you have any ideas to test this?

Copy it into a program in the Arduino IDE, compile it, upload it and see whether it produces the expected results perhaps.

Just change logf to log.

Pete

el_supremo:
Just change logf to log.

Pete

#define logf log

http://www.nongnu.org/avr-libc/user-manual/group__avr__math.html#gaccce424ce6effa1bfd476479d55dde9c

I've been playing with that code and it won't work as-is on Arduino. The random() function returns a long integer but RAND_MAX is only 32767 so the calculation won't produce the expected distribution.
One easy way to fix it is to use random(RAND_MAX) which will force random to produce the required range of numbers.
Try this code to play with it:

// From: http://forum.arduino.cc/index.php?topic=292956.0

//#include <math.h>
//#include <stdlib.h>

float nextTime(float rateParameter)
{
  return -log(1.0f - random(RAND_MAX) / ((float)RAND_MAX + 1)) / rateParameter;
}

void setup(void)
{
  // seed the random number generator
  // Not the best way, but better than nothing
  randomSeed(analogRead(0));
  
  Serial.begin(9600);
  while(!Serial);
  delay(1000);
  
//  Serial.println((float)RAND_MAX+1,6);
  // The first value returned from random() always seems
  // to be out to lunch compared with the rest of the sequence
  // so throw away the first number
  nextTime(.5);
  // Print 50 values using an average of 40
  for(int i = 0; i<50;i++) {
    Serial.println(nextTime(1./40.),6);
  }
  
  // Check that the average really is close to 40
  // This can take several seconds to complete
  float sum = 0;
#define LOOP_COUNT 32000
  for(int i=0;i<LOOP_COUNT;i++) {
    sum += nextTime(1./40.);
  }
  // It printed Avg = 40.0757
  Serial.print("Avg = ");
  Serial.println(sum/LOOP_COUNT,4);
}

void loop(void)
{
}

Pete

Okay, thanks for the help. I'll do that then :slight_smile: