Skip to content

Help with functions (iterations)

3 messages · Letticia Ramlal, jim holtman, Mark Wardle

#
Hello: 
I am a bit confused by this problem. Can anyone give me some advice on this I would greatly appreciate it. Thank you for all your help.
 
Need to create a for loop that saves the estimate of pi from each 0f 100 separate iterations and store it in a numeric vector (of length 100). The for loop should be placed in a function that allows the user to vary the sample size, the simulation size, the integration limits and the input function. In addition construct a histogram of the estimates and include a red vertical line at pi.
 
ex1.fcn<-function(x){
h<-4/(1+x^2)
return(h)
}
n=1000
a=0
b=1
my.rand.x=runif(n,min=a,max=b)
pi.MC = ((b-a)/n)*sum(ex1.fcn(my.rand.x))
#
I think this might be what you want:

ex1.fcn<-function(x){
h<-4/(1+x^2)
return(h)
}

my.pi <-
function(sample.size, sim.size, low, hi, func)
{
    # create output vector
    result <- numeric(sample.size)
    for (i in seq(sample.size)){ # loop for 'sample.size' times
        my.rand.x <- runif(sim.size, low, hi) # create random numbers
        result[i] <- ((hi - low) / sim.size) * sum(func(my.rand.x))
    }
    return(result)  # return the vector
}

pi.MC <- my.pi(100, 1000, 0, 1, ex1.fcn) # call the function
hist(pi.MC)  # plot histogram
On 9/29/07, Letticia Ramlal <lramlal at claflin.edu> wrote:

  
    
#
Dear Letticia,

Are you using R-help for your homework?

See your previous postings:


1. 15th September:

With a single R command complete the following:
create a vector calles seqvec that repeats the sequence 1, 3,6,
10,15,21.( I was trying to use c() but this does not work)
create a 5-row, 6-column matirx from seqvec wuth each row containg the
sequence from before
and complete the two task above in a single step.


2. 16th September

iven the following data for a data set called airquality. To identify
the nature of the objects from the data set airquality example "Ozone"
would it be best to use the command is. like
is.character(airquality$Ozone) ....... I tried
attributes(airquality$Ozone) but it came up null. Would there be a
better way to identify these objects.

3. 27th September

Using a 3-level input factor alternative so that a function(below) can
compute both a two-sided and one-sided p-values. Making the two-sided
test the default. And produce output information about which
alternative was tested.

4. Today

Need to create a for loop that saves the estimate of pi from each 0f
100 separate iterations and store it in a numeric vector (of length
100). The for loop should be placed in a function that allows the user
to vary the sample size, the simulation size, the integration limits
and the input function. In addition construct a histogram of the
estimates and include a red vertical line at pi.

Mark
On 29/09/2007, Letticia Ramlal <lramlal at claflin.edu> wrote: