Lab 5 - Calculating the cube root

By now, you should have some experience setting up a simple program. Let’s try another problem similar to our first homework problem. Instead of working on the square root problem, let’s see if we can figure out the cube root. This time, we will let a mathematician tell us how to do this!

The Problem statement

If X is the number we want the cube root of, and A is our guess, then X should equal A*A*A.

The scheme we will use

Here is what Isaac Newton has to say on the matter:

Start off with some guess for A. (You might try something simple like X/2 as a start.) Calculate each new guess using this formula:

A = 1/3 *( X/(A*A) + 2 * A)


You might wonder why all those parentheses are in there. I want to make sure we ask the computer to evaluate the right formula.

The line above is an “assignment statement”. The variable “A” appears on both sides of the equal sign. On the right side, the value for “A” is the previous guess. We evaluate the formula to produce a new guess, and save this new guess in the variable “A” for the next pass through the loop. You stop when the difference between the previous guess and the next guess is small enough to suit you.

Your assignment

Using the basic flow of the lab4 as a guide, and the example we worked in class, create a new C++ program in a file called cuberoot.cpp. Your program should prompt the user for an input number. It should then use the scheme shown above to generate an initial guess for the cube root of that number. It should then loop generating a new guess until the guess is accurate enough to suite you. (You get to pick the accuracy, but it should be better than a few digits past the decimal point. Think about how accurate your calculator is and see if you can do at least that well.

You can read a number from the user using this:

double  mynum;


cin >> mynum;

This example reads in a real number (with a decimal point in it). The angle brackets go toward the variable that will receive the input. The user enters a number, then presses the “return” (or “enter”) key.

As you test your program, print out each guess using a line like this”

Current guess for the cube root is x.xxxxxx, this is off by x.xxxxx

You should see a number of these lines until you decide the accuracy is good enough.

Now, run the program on a number of values you pick. Make sure you see how well you are doing. Your final output should give the final answer to the user. You decide how to display that.


There are hints on how to approach this problem in Homing in on an answer

What to turn in

Submit your cuberoot.cpp program source file on Blackboard in the Lab6 Lab area.