• Advertisement
Sign in to follow this  

Random percent

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
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 this post


Link to post
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 this post


Link to post
Share on other sites
Quote:
Original post by Paulsburbon
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.

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 this post


Link to post
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 this post


Link to post
Share on other sites
Quote:
Original post by erissian
For 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 this post


Link to post
Share on other sites
Quote:
Original post by oliii
rand() [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 this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement