Random sample generator from given pdf
5 views (last 30 days)
Show older comments
Hello everybody, I am a new user! I have a question regarding random sample generation in Matlab.
I have pdf function: 3/4(2x-x^2), x is on interval from 0 to 2. I have to generate sample that has the same distribution as mentioned before. What I have done so far: I calculated cdf by integrating and then obtained cdf^-1. I cannot solve the cdf^-1 equation for random x (from 0 to 1) as cdf^-1 is not solvable in Real numbers.
Am I doing something wrong? Any help would be greatly appreciated! Thanks in advance, Klemen.
0 Comments
Accepted Answer
Roger Stafford
on 5 Feb 2014
The cdf you obtained was presumably F(x) = -1/4*x^3+3/4*x^2. It is quite possible to solve for its inverse, since that involves only the solution of the cubic equation
-1/4*x^3+3/4*x^2 = p
This particular cubic can be solved as follows:
p = rand;
a = atan2(2*sqrt(p*(1-p)),1-2*p);
x = 1+2*cos(a/3-2*pi/3);
You can verify this by checking that x always lies between 0 and 2 and comparing -1/4*x^3+3/4*x^2 with p in a number of cases.
Therefore you can generate n random values with the desired distribution as follows:
p = rand(n,1);
a = atan2(2*sqrt(p.*(1-p)),1-2*p);
x = 1+2*cos(a/3-2*pi/3);
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!