[R] Function gives numeric(0) for every input

John jwd at surewest.net
Sun Nov 20 04:46:45 CET 2011


Though it seems a pity to even hint, what value have you assigned to "phat" 
and what is the value returned when the function runs?

On Saturday, November 19, 2011 18:52:20 alex_janssen wrote:
> Hi,
> 
> I am trying to code buffons needle in R for a class
> 
> This is my code w/ output from R, if anyone could tell me why this is
> happening it would be amazing,
> 
> I can generate correct results without putting the steps into a function but
> alas that is the assignment.
> 
> > buffon = function(n){
> 
> + x = NULL
> + theta = NULL
> + a = NULL
> + phat = numeric(0)
> + i = 1
> +
> + while ( i <= n){
> + x[i] <- runif(1,0,1/2)
> + theta[i] <- runif(1,0,pi/2)
> + a[i] <- 1/2 * (sin(theta[i])) - x[i]
> +
> +
> + if (a[i] <= 0)phat <- phat + 1
> + else phat<-phat
> + i <- i + 1
> +
> +  }
> + return(phat)
> + }
> 
> > buffon(10)
> 
> numeric(0)
> 
> Thanks Again
> 
> the response should be the number of times a[i] is less than or equal to
> zero, which i am calling phat
> 
> --
> View this message in context:
> http://r.789695.n4.nabble.com/Function-gives-numeric-0-for-every-input-tp40
> 87834p4087834.html Sent from the R help mailing list archive at Nabble.com.
> 
> ______________________________________________
> 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.



More information about the R-help mailing list