newtons method - Use inverse CDF to generate random variable in R -
First of all, I have no idea, Professor gave a wrong question. Anyway, I tried to generate Because / code>, Then, my code is such: the result may be less than zero. Your code has been modified like this: Obviously, the code is wrong, because I rejected the result of zero. So, my guess is to calculate my code properly If not, then there is another way to do this. Any gratitude is appreciated. You can [note: y The issue of this practice is to implement its version of Newton Rafsan technique, then tell me and I will remove the answer.] If I understand it correctly, then you can see the density of the function with the possibility < As you say, it can be from Then, F (x) ~ U (0,1) , where CDF
F (x) = 1- (1 + x) exp (-x) (For this CDF, you could not calculate with
x = g (f)) hand.
0 To
INF
uniroot () is out of the question therefore , I use the Newton method to write one.
f = function (x) {ifelse (x> = 0 , X * f (-x), 0)} in.C = function (n) {a = runif (n) g = for tap (i in 1: n) {del = 1 x = 2 while (abs ( Del) & gt 1e-12) {del = (1- (1 + x) * exp (-x) -a [i]) / f (x) x = x-del} g [i] = x} g} system however, if
f (x) is too small , And Newton is a step in the method, then there will be errors if the time (tt>
f = function (x) {ifelse (x> = 0, x * exp (-x), 0)} in.C = function AB (Dell) & gt; 1e-12) {if (x> = 0) {del = 1x = 2 for (i in 1: n) {del = 1x = 2} {a = runif (n) g = (1- (1 + x) * exp (-x) -a [i]) / f (x) x = x-del} second break if (x> gt = 0) g [i] = x} g [! Is.na (G)]} system.time (tt> lt; -c (100000) hist (tt, breaks = 70, right = F, freq = F), curve (f (x), = 0,
uniroot (.. ..) for it.
f = x * exp (-x) F = 1 - (1 + x) * exp (-x)
U [0,1] Generate Random Samples And
replaced by CDF inverse of F . The process is similar to those that have been posted, and except that you already have an expression for CDF.
f < - function (x) x * exp (-x) F & lt; - Function (X) 1- (1 + x) * Exp (-x) F.inv & lt; - Function (y) {uniroot (function (x) {f (x) -y}, interval = c (0,100)) $ root} F.inv & lt; - Vectorize (F.inv) x & lt; - seq (0, 10, length = 1000) y & lt; - seq (0,1, length = 1000) equal to (plot (x, f), type = "l", main = (x), plus (x, f), type = "l", main = "F" ("F"), type = "L", main = "F (x) inverted CDF") / Pre>
X ~ U [0, 1] and
Z = F.inv (X) .
set.seed (1) x <- runif (1000, 0,1) # Random sample from URL [0,1] Z
Comments
Post a Comment