Path: news.mathworks.com!not-for-mail
From: "Sadik " <sadik.hava@gmail.com>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Help with Random Variable Generation
Date: Fri, 16 Jan 2009 19:00:19 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 42
Message-ID: <gkqlg3$1i$1@fred.mathworks.com>
References: <gkqh11$osq$1@fred.mathworks.com>
Reply-To: "Sadik " <sadik.hava@gmail.com>
NNTP-Posting-Host: webapp-03-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1232132419 50 172.30.248.38 (16 Jan 2009 19:00:19 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Fri, 16 Jan 2009 19:00:19 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1666517
Xref: news.mathworks.com comp.soft-sys.matlab:512105


"Omega69 Omega69" <Omega69@gmail.com> wrote in message <gkqh11$osq$1@fred.mathworks.com>...
> Hi everybody,
> I'm trying to generate a random variable which probability density function is:
> f(x)=1-|x|,    -1<=x<=1
> To do that, I have calculated cumulative distribution function, which is (if I have not made any mistake...):
> F(x)= 0          if         x<-1
>           x?/2+x+1/2       if      -1<=x<=0
>          -x?/2+x+1/2       if       0<=x<=-1
>           1                       if        x>1
> 
> Now, I declare u=F(x) (where u is a uniform variable), and I try to isolate x to get F^-1(u), and then declare them in Matlab, but here is where I have problems:
> 
> 1) I know how to isolate x when -1<=x<=0, and I get x=sqrt(2*u)-1, but I don't know how to isolate it when 0<=x<=-1, any idea for this?
> 
> 2) And the other part is that I don't know how to write this into Matlab. I have try this:
> N=1000;
> u1=rand(N,1);
> u2=rand(N,2)
> X=(sqrt(2*u1)-1)*(u2(N,1)<0,5)+((the thing I don't know how to isolate))*(u2>0.5);
> 
> But the results I think that are wrong.
> 
> Anyone has any idea to get this correct?
> 
> Thank you very much in advance!!

Hello Omega69,

1) You have already found the function so the inverse for the positive part will be 

x = 1 - sqrt(2*(1-y))

This is because x-1 will be negative in the range 0 < x < 1. So you choose the negative square root.

2) Your inverse is one-to-one. So you don't need to generate a second uniform random variable.  Your code should be

N=1000;
u1=rand(N,1);

X=(sqrt(2*u1)-1).*(u1<0.5)+(1 - sqrt(2*(1-u1))).*(u1>=0.5);

It seems to work. Hope this helps.