• Forums
• Posts
Latest Posts
Active Posts
Recently Visited
Search Results
• Page Extras
• Forum Themes
• AVR Freaks

### LockedRandom Number

Author
OscarTheGrouch
Super Member
• Total Posts : 339
• Reward points : 0
• Joined: 2010/11/29 18:07:28
• Location: 0
• Status: offline
0

# Random Number

Hello all,
I've come to the Microchip Brain Trust again for helpful information.
So far I've never been let down, so here goes ..
I need a random number generator function like this ..
/****************
* Function: void LoadRandom(uint8_t r, uint8_t k);
* Overview: Load Register r (0 <= r <= 3) with random number in range (0 <= random number < k) (max k = 256)
****************/
I know about using srand(); and rand(); but what I can't figure out is how to limit the random number to less than 'k'.
BTW 'k' can be as small as 4.
Thanks.
Don

jtemples
عُضْوٌ جَدِيد
• Total Posts : 11982
• Reward points : 0
• Joined: 2004/02/13 12:31:19
• Location: Southern California
• Status: offline
Re: Random Number 2017/07/05 18:55:07 (permalink)
+2 (2)
rand() % k is the most common method, but it isn't the best method if you're looking for good quality random numbers.
OscarTheGrouch
Super Member
• Total Posts : 339
• Reward points : 0
• Joined: 2010/11/29 18:07:28
• Location: 0
• Status: offline
Re: Random Number 2017/07/05 19:06:21 (permalink)
0
jtemples
rand() % k is the most common method, but it isn't the best method if you're looking for good quality random numbers.

Thanks. The '%' does what ?
It doesn't have to be great it's just to get a random time to run a particular animation on the 3D Cube I'm working on.
It also picks a LED 0->4 index.
I'll check it out.
Don
1and0
Access is Denied
• Total Posts : 11155
• Reward points : 0
• Joined: 2007/05/06 12:03:20
• Location: Harry's Gray Matter
• Status: offline
Re: Random Number 2017/07/05 19:07:59 (permalink)
+4 (4)
The % is the modulus operator.

http://c-faq.com/lib/randrange.html

NorthGuy
Super Member
• Total Posts : 6307
• Reward points : 0
• Joined: 2014/02/23 14:23:23
• Status: online
Re: Random Number 2017/07/05 19:19:03 (permalink)
0
Multiplication is probably faster:

`r = (rand()&0xff)*(k+1) >> 8;`

jtemples
عُضْوٌ جَدِيد
• Total Posts : 11982
• Reward points : 0
• Joined: 2004/02/13 12:31:19
• Location: Southern California
• Status: offline
Re: Random Number 2017/07/05 19:20:01 (permalink)
+1 (1)
You said "less than 4", % 4 will give you that but will not give you 0-4.
OscarTheGrouch
Super Member
• Total Posts : 339
• Reward points : 0
• Joined: 2010/11/29 18:07:28
• Location: 0
• Status: offline
Re: Random Number 2017/07/08 17:56:50 (permalink)
+1 (1)
I see, then I will pass 5 to get random index number. Thanks
Gort2015