title: Rejection Sampling to generate Normal samples from Cauchy samples
body: <p>I tried my luck on coding a rejection sampling method to generate a sample that follows a normal distribution. The samples look like normal distributions on first glance but the p-value of the Shapiro-Wilk test is always &lt;0.05. I don't really know where I turned wrong and I only got the pseudo-code from my teacher (its NOT homework). Any help is appreciated. Below my code:</p>
  
  <pre><code>f &lt;- function(x,m,v) {    #target distribution, m=mean,v=variance
    dnorm(x,m,sqrt(v))
  }
  
  g &lt;- function(x,x0,lambda) {  #cauchy distribution for sampling
    dcauchy(x,x0,lambda)
  }
  
  genSamp &lt;- function(n,m,v) {  #I want the user to be able to choose mean and sd
                                #and size of the sample
    stProbe &lt;- rep(0,n)         #the sample vector
    interval = c(m-10*sqrt(v),m+10*sqrt(v)) #wanted to go sure that everything
                                            #is covered, so I took a range
                                            #that depends on the mean
    M = max(f(interval,m,v)/g(interval,m,v))  #rescaling coefficient, so the cauchy distribution
                                #is never under the normal distribution
    #I chose x0 = m and lambda = v, so the cauchy distribution is close to a
    #the target normal distribution
  
    for (i in 1:n) {
      repeat{
        x &lt;- rcauchy(1,m,v)
        u &lt;- runif(1,0,max(f(interval,m,v)))
        if(u &lt; (f(x,m,v)/(M*g(x,m,v)))) {
          break
        }
      }
      stProbe[i] &lt;- x
    }
  
    return(stProbe)
  }
  </code></pre>
  
  <p>Then I tried it out with:</p>
  
  <pre><code>test &lt;- genSamp(100,2,0.5)
  hist(test,prob=T,breaks=30)#looked not bad
  shapiro.test(test) #p-value way below 0.05
  </code></pre>
  
  <p>Thank you in advance for your help.</p>