A Simple R Program

Not only can R be used for statistical analysis, but I find it extremely useful for other tasks such as performing quick calculations, running simulations, and for general overall work that is suited to any scripting language. As an example of the simplicity of R, a small script is presented that calculates the value of PI by the Archimedian method of polygons. There are only 16 lines of code and 5 of those are used to print out the results to the console.

# Pi by the Archimedian Method #

# Calculate PI by approximating the circumfrence of a circle
# of unity radius with circumscribed and inscribed polygons.  
# This method provides upper and lower bounds of the value of PI

# Define the radius of the base circle
R <- 1

# Define an initial number of polygon sides
n <- 4

# Define a convergence tolerance
# The analysis will halt when either of the circumscribed or 
# inscribed polygon perimiters is within this tolerance value 
# of PI as determined by the machine.
conv <- 1e-5

# Initialize the residuals
R_i <- 2 * conv
R_c <- 2 * conv

# Begin loop
# The loop continues unitl one of the residuals is less than 
# the convergence tolerance.  Each iteration increases the number 
# of sides of the polygons by one.

while(R_i > conv || R_c > conv){

  # Perimiter of inscribed polygon
  L_i <- n*R*sin(pi/n)

  # Perimiter of circumscribed polygon
  L_c <- n*R*tan(pi/n)

  # Calculate the Residuals
  R_i <- pi - L_i
  R_c <- L_c - pi

  # Increment the number of polygon sides
  n <- n + 1

# Print the results to the console
cat("The number of iterations was:  ", n - 4,"n")
cat("The number of polygon sides is:  ", n,"n")
cat("Upper Bound:  ", L_c,"n")
cat("Lower Bound:  ", L_i,"n")
cat("Maximum Residual:  ", max(R_i,R_c),"n")

# End Code

The number of iterations was:   1014 
The number of polygon sides is:   1018 
Upper Bound:   3.141603 
Lower Bound:   3.141588 
Maximum Residual:   9.992821e-06 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>