Skip to content

Instantly share code, notes, and snippets.

@JaneLSumner
Last active October 17, 2015 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JaneLSumner/220982b51c57b286d5a7 to your computer and use it in GitHub Desktop.
Save JaneLSumner/220982b51c57b286d5a7 to your computer and use it in GitHub Desktop.
This code is intended to allow students to visualize the logic behind calculating definite integrals using the limit of a Riemann sum. It was written for Political Science 508, a mandatory course for first-semester political science Ph.D. students at Emory University, by Jane Lawrence Sumner.
## Definite Integral as the Limit of a Riemann Sum: Visualizing the Logic
## Jane Lawrence Sumner
## TA, POLS 508, Fall 2015
#### INPUTS HERE ####
a <- 1 ## lower bound
b <- 10 ## upper bound
n <- 20 ## number of iterations
fxn <- function(x){
eq <- x^2 ## the function to evaluate
return(eq)
}
#####################
#### WHERE THE MAGIC HAPPENS ####
x <- seq(a-1,b+1,.01) ## Set the x-axis to visualize.
fx <- fxn(x) ## Evaluate function for plotting.
plot(x,fx,type="l") ## Plot the function.
abline(v=c(a,b),lty=3) ## Plot the lower and upper bounds.
abline(h=0) ## Plot the x-axis.
summation <- 0 ## Start with a sum of zero.
xlast <- a ## The leftmost bound for boxes.
for(i in 1:n){
x <- a+i*(b-a)/n ## The formula starts here.
fx <- fxn(x) ## Evaluate function at value.
segments(x0=xlast,x1=x,y0=fx)
segments(y0=0,y1=fx,x0=x)
polygon(c(xlast,x,x,xlast),c(0,0,fx,fx),col=i,density=45)
summation <- summation + fx ## Add this value to previous sum.
xlast <- x ## Set new left bound for box.
}
summation <- (b-a)/n*summation ## Multiply sum by (b-a)/n
title(main=paste("The Integral is Approximately ",round(summation,3),sep=""))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment