Go Down

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

#### Personman

##### Nov 11, 2009, 10:58 pm
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

#1
##### Nov 11, 2009, 11:02 pm
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

#2
##### Nov 12, 2009, 12:43 am
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

#### Personman

#3
##### Nov 12, 2009, 07:00 pm
@ 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

#4
##### Nov 12, 2009, 08:15 pm
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

#5
##### Nov 12, 2009, 10:43 pm
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

#6
##### Nov 12, 2009, 10:57 pm
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

#7
##### Nov 13, 2009, 12:15 am
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

#8
##### Nov 13, 2009, 12:17 am
So it's clear. The code I posted is from Arduino.
WMath.cpp

Go Up

Please enter a valid email to subscribe