/* CalculateSphereVolume.java CIS 160 David Klick 2004-11-21 This program uses a calculus-style technique to determine the volume of a sphere. The sphere is sliced into disks which we can use to roughly approximate the volume. Each successive volume calculation slices the sphere into twice as many pieces, which makes the volume calculation increasingly accurate. When two successive volume calculations fall within the acceptable tolerance level, then the program is done. The program then displays how the volume is related to Pi * r^3. We know that the area of a circle is Pi * r^2, so the volume must be related to Pi * r^3 by some factor. The answer should, of course, be a number close to 4/3 (1.33333...). It should be noted that we get our initial upper bound for the volume of the sphere by calculating the volume of its bounding cylinder (Pi * r^2 * 2r). Every successive calculation produces a smaller and smaller number for the volume. If you want a more precise answer, just change the value of the variable "tolerance", recompile, and rerun the program. */ import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class CalculateSphereVolume { public static void main(String[] args) throws IOException { BufferedReader kbd = new BufferedReader( new InputStreamReader(System.in)); double oldVolume = 0.0; double newVolume = 0.0; double radius = 0.0; int steps = 1; double change = 0.0; double tolerance = 0.0000001; while (true) { try { System.out.print("Enter radius of sphere: "); radius = Double.parseDouble(kbd.readLine()); break; } catch (NumberFormatException e) { System.out.println("Error: Invalid number!"); } } // only allow positive radius radius = Math.abs(radius); // start with volume of the bounding cylinder newVolume = 2.0 * Math.PI * radius * radius * radius; do { oldVolume = newVolume; steps *= 2; double width = radius / steps; double x = width / 2.0; newVolume = 0.0; for (int i=1; i<=steps; x+=width, i++) newVolume -= x * x; newVolume = (newVolume + radius * radius * steps) * 2 * Math.PI * width; System.out.println("Volume = " + newVolume + " (steps: " + steps + ")"); change = Math.abs(newVolume - oldVolume); } while (change > tolerance); double factor = newVolume / (Math.PI * radius * radius * radius); System.out.println("\n\n" + factor + " times PI * r^3"); } }