Hi, In S+/R, is there an easy way to generate random numbers with a probability distribution specified by an exact user-defined function? For example, I have a function: f(x) = 1/(365 * x), which should be fitted for values of x between 1 and 100,000 How do I generate random numbers with a probability distribution that exactly maps the above function? Nick This email and any attachments may contain information t...{{dropped:15}}
Robert A LaBudde
2010-Apr-29 11:19 UTC
[R] Random numbers with PDF of user-defined function
At 05:40 AM 4/29/2010, Nick Crosbie wrote:>Hi, > >In S+/R, is there an easy way to generate random numbers with a >probability distribution specified by an exact user-defined function? > >For example, I have a function: > >f(x) = 1/(365 * x), which should be fitted for values of x between 1 and >100,000 > >How do I generate random numbers with a probability distribution that >exactly maps the above function? > >NickFirst of all, your pdf should be f(x) = 1 / [x log(100000)], if x is continuous. Second, compute the cdf as F(x) = ln(x) / log(100000). Third, compute the inverse cdf as G(p) = exp[p log(100000)] Finally, to generate random variates, use G(u), where u is a uniform random variate in [0,1]. In R, > G<- function (p) exp(p*log(100000)) > G(runif(5)) [1] 11178.779736 9475.748549 65939.487801 94914.354479 1.694695 ===============================================================Robert A. LaBudde, PhD, PAS, Dpl. ACAFS e-mail: ral at lcfltd.com Least Cost Formulations, Ltd. URL: http://lcfltd.com/ 824 Timberlake Drive Tel: 757-467-0954 Virginia Beach, VA 23464-3239 Fax: 757-467-2947 "Vere scire est per causas scire"
On 29/04/2010 5:40 AM, Nick Crosbie wrote:> Hi, > > In S+/R, is there an easy way to generate random numbers with a > probability distribution specified by an exact user-defined function? > > For example, I have a function: > > f(x) = 1/(365 * x), which should be fitted for values of x between 1 and > 100,000 > > How do I generate random numbers with a probability distribution that > exactly maps the above function? >You can use sample() with the prob argument set to the values of f(x). You probably want replace=TRUE as well. Duncan Murdoch> Nick > > This email and any attachments may contain information t...{{dropped:15}} > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >