Random max & min/max function C code

Hello,

Would someone be able to point me to where I could find the C code used for the random max and random min/max functions. I would like to port them to an ATtiny project I am working on among other things.

I've found various versions online however I've never had any issues using this function so If I could continue to use it that would be great. :slight_smile:

Thanks

extern "C" {
  #include "stdlib.h"
}

void randomSeed(unsigned int seed)
{
  if (seed != 0) {
    srandom(seed);
  }
}

long random(long howbig)
{
  if (howbig == 0) {
    return 0;
  }
  return random() % howbig;
}

long random(long howsmall, long howbig)
{
  if (howsmall >= howbig) {
    return howsmall;
  }
  long diff = howbig - howsmall;
  return random(diff) + howsmall;
}

:slight_smile:

In avr-libc there is already a rand() function which you can use with the attiny devices:

http://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#ge23144bcbb8e3742b00eb687c36654d1

@ programmer

I am aware of that however their is no, at least no std, max or min/max functionally. But thanks for the heads up.

@AlphaBeta

Thanks

So what do you mean by random max, random min/max function??

Do you want to compute a min, max or std value of something?

Or do you want to generate a random value in an specified interval, from min to max?

To generate a random number within a specified range.

I saw this example online however I wanted to see the Arduino code version. If it differs I would prefer to use it as opposed to what I found.

//generates a psuedo-random integer between 0 and max 
int randint(int max) 
{ 
    return int(max*rand()/(RAND_MAX+1.0)); 
} 

//generates a psuedo-random integer between min and max 
int randint(int min, int max) 
{ 
    if (min>max) 
    { 
        return max+int((min-max+1)*rand()/(RAND_MAX+1.0)); 
    } 
    else 
    { 
        return min+int((max-min+1)*rand()/(RAND_MAX+1.0)); 
    } 
}

In this example min and max are not functions, they are parameters, so there is no need for any standard min or max functionality. You only need the rand() function.

Correct. I would like to make a function for future use. So what I am really interested in is the code used in the the Arduino function or comparable code to write a similar function.

I could always rewrite that example or the code inside the Arduino function each time but I'm much to lazy for that. :wink:

So it's clear. The code I posted is from Arduino.
WMath.cpp