# random number generating RANDI with percentage

38 views (last 30 days)
Takim Mustakim on 7 Nov 2022
Answered: James Tursa on 7 Nov 2022
How to generating random number with percentage:
value = 0 - 14 with 86%
value = 15 - 28 with 14%
with 1000 array
Torsten on 7 Nov 2022
Is 86% and 14% also a probability (i.e. random numbers between 0 and 14 are generated with probability 0.86 and random numbers between 15 and 28 are generated with probability 0.14) or a fixed percentage ?

Image Analyst on 7 Nov 2022
If it's not homework, you can try this:
x = [0, 14, 28];
y = [0, .86, 1.0];
plot(x, y, 'b.-', markerSize=30, LineWidth=2)
grid on;
title("Cumulative Distribution Function")
% Get half a million random numbers
n = 500000
n = 500000
r = GetRandom(n);
% Count # less than 14. Should be 86% of them.
pct14 = sum(r < 14) / n
pct14 = 0.8596
% Count # more than 14. Should be 14% of them.
pct14 = sum(r > 14) / n
pct14 = 0.1404
% Function to give 86% of numbers in the range of 0-14 and 14% of the
% numbers in the range 14-28.
function r = GetRandom(n)
r = rand(1, n);
if r < 0.86
r = r / 0.86;
else
slope = .14 / 14;
% y - y0 = slope * (x - x0)
% Find x
% x = (y - y0) / slope + x0
% y0 = 0.86. x0 = 14.
r = (r - 0.86) / slope + 14;
end
end
Uses the concept of inverse transform sampling.
If it's your homework you can't turn in my code.
Torsten on 7 Nov 2022
I think you overlooked the "randi" in the title.

Walter Roberson on 7 Nov 2022
If you have the Statistics Toolbox, use randsample()
If not then:
Find a number, S, such that S*p is an integer for each probability in the vector p. If you have probabilities such as sqrt(2)/2 that are mathematically irrational then you will need to find a good approximation of an integer rather than being exact.
Once you have S, take each element Value(K) and repeat it round(S*p(K)) times, and collect the repeated values in a vector. For example for .86 and .14 you could use S = 50 and repeat the first value 43 times and the second value 7 times.
Now to draw with weights, use randi() on the length of the vector with repetitions, to pick out elements of the vector. The probability that any one (repeated) element will be drawn will be proportional to the number of repetitions divided by the total length of the vector. For example, 43 copies of 0 out of 50 elements gives a 43/50 = 0.86 probability that 0 would be drawn.

James Tursa on 7 Nov 2022
One way:
n = 1000;
p = 0.86;
r = rand(n,1);
x = r < p;
m = sum(x);
r(x) = randi([0,14],m,1);
r(~x) = randi([15,28],n-m,1);
Or one could re-use the random numbers already in r, but this seems a bit complicated:
n = 1000;
p = 0.86;
r = rand(n,1);
x = r < p;
r(x) = floor(15*r(x));
r(~x) = floor(14*(r(~x)-p)/(1-p)) + 15;

### Categories

Find more on Logical in Help Center and File Exchange

R2021a

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by