Random percent
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.
RNG implementation agnostic formula is:
As nub as it is to admit I don't recall how % works with floats. But the above certainly works with integer RNGs.
-me
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
For floats in C, I typically go with
Edit: Oliii showed me the light.
[Edited by - erissian on June 22, 2007 3:27:51 AM]
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]
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).
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.
Quote:Original post by erissian
For floats in C, I typically go withfloat 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
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. */
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement