Circle in the Square

Circle in the Square - Darts D BULLSEYE<-function() B {

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
#Calculate the Area of A circle in a box - SIMPLE METHOD! # Area =function(n) A { z=NULL for (i in 1:n) f { u1=runif(1) u2=runif(2) x=2*u1-1 y=2*u2-1 z[i]=x^2+y^2 } return(length(z[z<=1])/length(z)) r } #Draws a Circle # CIRCLE <- function(title,loco) C { op <- par(bg = "white") x <- seq(-1,1, len=61) l y <- seq(-0.01,0.01, len=61) #R needs to know bounds of graphic. plot(c(x,x), c(sqrt(1-(x)^2),-sqrt(1-(x)^2)), type="n", c main=title,ylab="Y",xlab="X") #upper part of outer circle o lines(x, sqrt(1-(x)^2), type="l", pch=21, bg=par("bg"), col = "blue", cex=.6) #lower part of outer circle # lines(x, -sqrt(1-(x)^2), type="l", pch=21, bg=par("bg"), col = "blue", cex=.6) " #upper part of inner circle lines(y, sqrt(0.01-(y)^2), type="l", pch=21, bg=par("bg"), col = "black", cex=.6) b #lower part of inner circle lines(y, -sqrt(0.01-(y)^2), type="l", t pch=21, bg=par("bg"), col = "black", cex=.6) par(op) }#Calculates an Area Using
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Darts D BULLSEYE<-function() B { cat("\n") cat("*****BULLS EYE*****","\n") cat("The Goal: The area of the circle in the square (-1,-1),(-1,1),(1,-1),(1,1)","\n") T cat(" ","\n") cat("\n") #draw the circle # CIRCLE("CIRCLE",0) #Determine the number of darts thrown ANSWER <- readline("What is the sample size? ") r SSize <- as.numeric(ANSWER) cat("\n") ANSWER <- readline("Fire darts one at a time? ") if (substr(ANSWER, 1, 1) == "y") { cnt <- 0 for (i in 1:SSize) 1 { ANSWER <- readline("Hit ENTER to FIRE WHEN READY!") cat("\n") cat("FIRE!!!\n") c cat("\n") x=2*runif(1)-1 y=2*runif(1)-1 points(x,y) if (x^2+y^2<=1) cnt=cnt+1 ( } pct <- cnt/SSize } else { xdarts<-2*runif(SSize)-1 ydarts<-2*runif(SSize)-1 y points(xdarts,ydarts) #darts in circle circle <- xdarts^2+ydarts^2 x pct<-length(circle[circle<=1])/SSize } return(4*pct) r }BULLSEYE()...
View Full Document

This note was uploaded on 11/16/2010 for the course STAT 340 taught by Professor Xu(sunny)wang during the Spring '09 term at Waterloo.

Ask a homework question - tutors are online