Skip to content
Prev 283887 / 398502 Next

Generate data - function

On Tue, Jan 31, 2012 at 01:59:13PM -0500, Val wrote:
Hi.

The following is a simpler solution, where we can start
with a function f(x), which is a multiple of the required
density, so it specifies its shape.

  #an example, use a function approximating your graphs
  f <- function(x) { 0.7 - 1.25*((x - 1)^2 - 0.4)^2 }

  #plot function f(x)
  x <- seq(0, 2, length=51)
  y <- f(x)
  plot(x, y, type="l")

  #plot an approximate distribution function
  xDistr <- x
  yDistr <- cumsum(y)/sum(y)
  plot(xDistr, yDistr, type="l")

  #generate random sample
  library(splines)
  invDistr <- interpSpline(yDistr, xDistr)
  z <- predict(invDistr, runif(100000))$y

  #plot the empirical distribution function
  lines(sort(z), seq(0, 1, length=length(z)), col=2)

  #for a more accurate comparison subtract the line with slope 1/2
  plot(xDistr, yDistr - xDistr/2, type="l")
  lines(sort(z), seq(0, 1, length=length(z)) - sort(z)/2, col=2)

Hope this helps.

Petr.