# Random percent

This topic is 4141 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

If I wanted to get a random percent between two numbers that are different. How would I go about it? Say I take 10% and 25%. Is there a way in to come up with a random number inbetween every time I pass those numbers thru a function? Thanks.

##### Share on other sites
In what language?

##### Share on other sites
RNG implementation agnostic formula is:

randomValue = (randomNumberGenerator() % (Max - Min)) + Min;

As nub as it is to admit I don't recall how % works with floats. But the above certainly works with integer RNGs.

-me

##### Share on other sites
For floats in C, I typically go with
float randf(float a, float b) { return (rand()/(float)RAND_MAX)*(b-a)+a;}

Edit: Oliii showed me the light.

[Edited by - erissian on June 22, 2007 3:27:51 AM]

##### Share on other sites
Quote:
 Original post by PaulsburbonIf I wanted to get a random percent between two numbers that are different. How would I go about it? Say I take 10% and 25%. Is there a way in to come up with a random number inbetween every time I pass those numbers thru a function? Thanks.

First off, you haven't really given us any language to operate in. Strictly speaking, assuming you have a function f() that returns a random value in [0, 1], then you can generate a random number between two values (inclusive) like so: v = min + f() * (max - min).

##### Share on other sites
Thanks for the reply. I thought the basic idea would be the same in all the languages. Very sorry about that. I'm working with visual basic but I think I have the general idea now. I'll try something in the morning and post if I run into a problem. Thanks for all the quick replies.

##### Share on other sites
Quote:
 Original post by erissianFor floats in C, I typically go with float randf(float a, float b) { return (rand()/(RAND_MAX-1.0f))*(b-a)+a;}

isn't it

float randf(float a, float b) { return (rand()/(float)(RAND_MAX))*(b-a)+a;}

rand() [0, 65535], randmax = 65535 I believe

##### Share on other sites
Quote:
 Original post by oliiirand() [0, 65535], randmax = 65535 I believe

Ah, so you're right. I wonder where I picked that up?

From stdlib.h:
#define   RAND_MAX        2147483647/* Return a random integer between 0 and RAND_MAX inclusive.  */

##### Share on other sites
RAND_MAX is implementation defined yes?

##### Share on other sites
Quote:
 Original post by rip-offRAND_MAX is implementation defined yes?

yes

1. 1
Rutin
46
2. 2
3. 3
4. 4
5. 5
JoeJ
19

• 13
• 10
• 12
• 10
• 13
• ### Forum Statistics

• Total Topics
632998
• Total Posts
3009808
• ### Who's Online (See full list)

There are no registered users currently online

×