SimplyKiwi
SimplyKiwi

Reputation: 12444

Random float between two numbers with percentage chances?

I know the title is not very clear on what I want to achieve so I will explain what I want to achieve in more depth.

Pretty much I have a method that returns a float between two numbers which looks like this:

- (float)randomFloatBetween:(float)num1 andLargerFloat:(float)num2 {
    return ((float)arc4random() / ARC4RANDOM_MAX) * (num2-num1) + num1;
}

Now I want to add a percentage chance to it. For example I need a float between 3 and 5 but there will be an 85% chance the number will be between 3 and 4 however there will still be that 15% chance that the number will be between 4 and 5.

Is this possible to do? I have tried looking at other S.O posts but none seem to want to accomplish this.

Thanks!

Upvotes: 0

Views: 901

Answers (3)

vacawama
vacawama

Reputation: 154671

You can do this with one random number if you scale it:

r = random();
if (r <= 0.85)
    n = 3 + (r / 0.85);
else
    n = 4 + ((r - 0.85) / 0.15);

This can be generalized. If your random number is between n1 and n3, and there is a p1 chance it is between n1 and n2, and a p2 chance it is between n2 and n3, (where n1 < n2 < n3, and p1 + p2 = 1) then

r = random();
if (r < p1)
    n = n1 + (r / p1)*(n2 - n1)
else
    n = n2 + ((r - p1) / p2)*(n3 - n2)

Upvotes: 2

Phillip Mills
Phillip Mills

Reputation: 31016

If you only need a uniform distribution for each interval, you can generate your number in two stages. The first stage picks the interval and the second stage uses the method you have to get the actual number.

e.g. If the first stage random, with a percentage range, is 0-to-84 call your method with 3 and 4; if it's 85-to-99 call with 4 and 5.

Upvotes: 1

rmaddy
rmaddy

Reputation: 318884

First get a random number between 0 and 1. If it's 0-0.85 then calculate the 2nd random number in the desired range. If it's 0.86-1.0 then calculate the 2nd random number in the other desired range.

BTW - arc4random is overkill and is meant for cryptography. Just use random (seed with srandom first)

Upvotes: 1

Related Questions