How to Best Create a Random Float in a Range Between Two Floats

How to best create a random float in a range between two floats

Let's recap:

rand() will generate a (psuedo-)random
float between 0 and 1.

rand(int) will generate a
(psuedo-)random integer between 0 and
int.

So something like:

def range (min, max)
rand * (max-min) + min
end

Should do nicely.

Update:

Just tested with a little unit test:

def testRange
min = 1
max = 100

1_000_000.times {
result = range min, max
print "ERROR" if result < min || result > max
}
end

Looks fine.

How to get a random number between a float range?

Use random.uniform(a, b):

>>> import random
>>> random.uniform(1.5, 1.9)
1.8733202628557872

Random 30 numbers (float) between 2 ranges (100 and 150 for example) that sums up to N

This function has four parameters: size, min, max, and sum- where size is the length of the array you want to produce. will return false if the mix/max/size combo you pass is an impossible task, meaning that either picking the minimum every time would still be too high OR picking the maximum every time would still be too low.

To create the array (called set), we pick size - 1 random numbers, each time subtracting the random number from our desired sum. It's important to not that we also check with each pick that the pick does NOT cause a situation where picking the minimum every time would still be too high OR picking the maximum every time would still be too low. If we find that that would be the case, our while loop scraps that random number and chooses a different one instead. Because we use this method to never set ourselves up for failure, we only have to pick size - 1 random numbers, and what's left over in our sum variable is guaranteed to be within our min/max range AND bring our total up to our original desired sum.

The bottleneck here is that we're asking for a random float between two numbers but then rejecting it if it doesn't fit our ulterior motives. Too many rejections can slow things down, so the more padding you leave to play with, the better this is likely to perform. For example, randomSet(10, 50, 100, 500); is virtually guaranteed to stall (because we'd have to pick exactly 50.00000 TEN times in a row- and what are the chances of that??), while randomSet(10, 50, 100, 750); will take virtually no time to finish successfully.

function randomSet(size, min, max, sum) {  if (min * size > sum || max * size < sum) return false;
var set = []; for (; size > 1; size--) { var randomNumber = rando(min, max, "float"); while (min * (size - 1) > sum - randomNumber || max * (size - 1) < sum - randomNumber) { randomNumber = rando(min, max, "float"); } set.push(randomNumber); sum -= randomNumber; } set.push(sum);
return set;}
var myRandomSet = randomSet(30, 100, 200, 4500);console.log(myRandomSet);console.log("SUM: " + myRandomSet.reduce((a, b) => a + b, 0));
<script src="https://randojs.com/1.0.0.js"></script>

Generate random floats excluding a range of numbers

Change the limits definition:

In [2]: limits = list(range(-10000000, -10000)) + list(range(10000, 10000000))

In [3]: from random import choice

In [4]: x = random.choice(limits)

This would work. You were trying to add two ranges which is not possible. You need to convert the range into list before adding it.

How to generate random float number in C

Try:

float x = (float)rand()/(float)(RAND_MAX/a);

To understand how this works consider the following.

N = a random value in [0..RAND_MAX] inclusively.

The above equation (removing the casts for clarity) becomes:

N/(RAND_MAX/a)

But division by a fraction is the equivalent to multiplying by said fraction's reciprocal, so this is equivalent to:

N * (a/RAND_MAX)

which can be rewritten as:

a * (N/RAND_MAX)

Considering N/RAND_MAX is always a floating point value between 0.0 and 1.0, this will generate a value between 0.0 and a.

Alternatively, you can use the following, which effectively does the breakdown I showed above. I actually prefer this simply because it is clearer what is actually going on (to me, anyway):

float x = ((float)rand()/(float)(RAND_MAX)) * a;

Note: the floating point representation of a must be exact or this will never hit your absolute edge case of a (it will get close). See this article for the gritty details about why.

Sample

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(int argc, char *argv[])
{
srand((unsigned int)time(NULL));

float a = 5.0;
for (int i=0;i<20;i++)
printf("%f\n", ((float)rand()/(float)(RAND_MAX)) * a);
return 0;
}

Output

1.625741
3.832026
4.853078
0.687247
0.568085
2.810053
3.561830
3.674827
2.814782
3.047727
3.154944
0.141873
4.464814
0.124696
0.766487
2.349450
2.201889
2.148071
2.624953
2.578719

Random float number generation

rand() can be used to generate pseudo-random numbers in C++. In combination with RAND_MAX and a little math, you can generate random numbers in any arbitrary interval you choose. This is sufficient for learning purposes and toy programs. If you need truly random numbers with normal distribution, you'll need to employ a more advanced method.


This will generate a number from 0.0 to 1.0, inclusive.

float r = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);

This will generate a number from 0.0 to some arbitrary float, X:

float r2 = static_cast <float> (rand()) / (static_cast <float> (RAND_MAX/X));

This will generate a number from some arbitrary LO to some arbitrary HI:

float r3 = LO + static_cast <float> (rand()) /( static_cast <float> (RAND_MAX/(HI-LO)));

Note that the rand() function will often not be sufficient if you need truly random numbers.


Before calling rand(), you must first "seed" the random number generator by calling srand(). This should be done once during your program's run -- not once every time you call rand(). This is often done like this:

srand (static_cast <unsigned> (time(0)));

In order to call rand or srand you must #include <cstdlib>.

In order to call time, you must #include <ctime>.

Get floating random numbers between -2 and 2 only using random.random in numpy?

np.random.random returns a random float between 0.0 and 1.0

so you can multiply by 4 and subtract 2 so the range would be -2.0 to 2.0

np.random.random(6)*4 - 2
array([ 1.41044053, -0.97521584, 1.55446329, -0.54314241, -1.55691897,
0.28276924])


Related Topics



Leave a reply



Submit