user475353
user475353

Reputation:

Calculating a Random for C++

This is probably a super easy question, but I just wanted to make 10000% sure before I did it. Basically Im doing a formula for a program, it takes some certain values and does things when them.....etc..

Anyways Lets say I have some values called:

N
Links_Retrieved
True_Links
True_Retrieved.

I also have a % "scalar" ill call it, for this example lets say the % scalar is 10%.

Links Retrieved is ALWAYS half of N, so that's easy to calculate. BUT I want True_Links to be ANYWHERE from 1-10% of Links_Retrieved.

Then I want True_Retrieved to be anywhere from The True_Links to 15% of Links_Retrieved. How would I do this? would it be something like

True_Link=(((rand()%(Scalar(10%)-1))+1)/100);

? I would divide by 100 to get the "percent" value IE .1 so it's be anywhere from .01 to .1?

and to do the True_retrieved it'd be

True_Retrieved=(rand()%(.15-True_Link))+True_Link;

am I doing this correct or am I WAYYYY off? thanks

Upvotes: 0

Views: 317

Answers (3)

jilles de wit
jilles de wit

Reputation: 7138

rand() produces values between 0.0 and 1.0 inclusive, you have to scale that output to the interval you want. To get a value fact1 between 0.01 and 0.1 (1%-10%) you'd do:

perc1 = (rand()/RAND_MAX)*9.0+1.0; //percentage 1-10 on the 0-100 scale
fact1 = perc1/100.0;  //factor 0.01 - 0.1 on the 0-1 scale

to get a value between perc1 and 0.15 you'd do:

percrange = (15.0 - perc1);
perc2 = (rand()/RAND_MAX)*percrange + perc1;
fact2 = perc2/100.0;

so your values become:

True_Links = fact1*Links_Retrieved;
True_Retrieved = fact2*Links_Retrieved;

This is sort-of-pseudocode. You should make sure parc1, perc2, fact1, fact2 and percrange are floating point values, and the final multiplications are done in floating point and rounded to integer numbers.

Upvotes: -1

ChRapO
ChRapO

Reputation: 337

Maybe it would be better to use advanced random generator like Mersenne Twister.

Upvotes: 0

MSalters
MSalters

Reputation: 179779

rand() is a very simple Random Number Generator. The Boost libraries include Boost.Random. In addition to random number generators, Boost.Random provides a set of classes to generate specific distirbutions. It sounds like you would want a distribution that's random between 1% and 10%, i.e. 0.01 and 0.1. That's done with boost::random::uniform_real(0.01, 0.1).

Upvotes: 2

Related Questions