Go Down

Topic: Random max & min/max function C code (Read 2 times) previous topic - next topic

Personman

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.  :)

Thanks

AlphaBeta

Code: [Select]
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;
}

:)

programmer


Personman

@ 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  

M Lundin

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?  

Personman

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.

Code: [Select]
//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));
   }
}

 

M Lundin

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.

Personman

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.  ;)    

AlphaBeta

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

Go Up