Created
August 29, 2015 10:46
-
-
Save mick001/c29bedaeb6fade21837d to your computer and use it in GitHub Desktop.
Volume of solids of revolution: the cone. Part 3. Full article at: http://www.firsttimeprogrammer.blogspot.com/2015/03/volume-of-solids-of-revolution-cone.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Solid of rotation: a cone | |
#------------------------------------------------------------------------------- | |
# Our function to generate the solid of rotation | |
foo <- function(x) | |
{ | |
return(0.5*x) | |
} | |
# This function integrates f^2 over the given [a,b] interval | |
# Assuming we're using only the positive half of the real line. | |
integrate <- function(f,a,b,dx=0.001) | |
{ | |
if(a > b) | |
{ | |
print('Please make sure b > a then enter again.') | |
return(0) | |
}else if(a == b) | |
{ | |
return(0) | |
} | |
partial_sum = 0 | |
while(a < b) | |
{ | |
partial_sum <- partial_sum + max(f(a)^2,f(a+dx)^2)*dx | |
a <- a + dx | |
} | |
return(partial_sum) | |
} | |
# Formula for the volume of a cone and comparison with the estimatation | |
cone_volume <- function(r,h,compare=T) | |
{ | |
v <- pi*h*r^2/3 | |
if(!compare) | |
{ | |
return(v) | |
}else | |
{ | |
v2 <- pi*integrate(foo,0,h) | |
error <- abs(v - v2)/v*100 | |
print(paste('We missed of:',error,'%')) | |
string_tp <- c(v,v2) | |
names(string_tp) <- c('Real volume','estimated volume') | |
print(string_tp) | |
} | |
} | |
# Let's approximate the volume | |
cone_volume(5,10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment