My task is to generate 5000 random numbers between -2 and 5
then count up how many of those values are between 2 and 3
This is what I have so far:
randNums=rand(1,5000); %Generate 5000 random values between 0 and 1
randNums=randNums*7-2; %Get those random values to be between -2 and 5
I understand that 7*1=7
and 0*7=0
so -2 from each = 7-2, but I do nut fully understand how to apply that again if the numbers were to be between 5,6 or -6 and 1.
My problem interpretation
You have random numbers in the interval (0,1). But you require random numbers in (a,b).
Solution
You simply have to scale and shift your interval.
Scale the interval:
The size/length of the interval (a,b) is b-a. To rescale the interval you have to multiply all your random values with b-a.
Shift the interval:
When you have scaled the interval you have numbers in the interval (0,b-a). You simply shift all numbers by adding the number a to it. Which leads to random numbers in the interval (a,b).
What you are referring to is called "Linear Interpolation". In some libraries it is called lerp
and usually it's implemented
float lerp(float v0, float v1, float t) {
return v0+(v1-v0)*t
}
So in your case v0
is -2, v1
is 7 and t
is the value between 0 and 1 you want to interpolate.
numbers = random('unif', -2, 5, 1, 1000);
count = sum(numbers > 2 & numbers < 3);