An Introduction to Numerical Methods in C++, Revised Edition

Chapter 2: Expressions, Statements and Functions

Overview

The following program implements a simple version of Newton's algorithm for extracting the square root of 10, starting with 3 as first approximation:

#include #include const double tolerance = 1.0E-10;double x = 3;main( ){       while (fabs(x*x - 10) > tolerance)              x = (x + 10/x)/2;        cout << "Square root of 10 is "             << x << "\n";}

When compiled and run, the program displays on the screen:

Square root of 10 is 3.162278

The result is correct to the default precision of the output operator, although the program is unsatisfactory in several ways. It is sufficient, however, for immediate purposes of exposition. Later we shall refine it, thereby introducing a number of helpful practices.

The small quantity tolerance, initialized to the value 10 ?10, is optionally declared const because it is not to be (and is not!) changed by the program. The successive approximations to the square root, starting with 3, are assigned to x. The core of the program takes the form of a conditional statement which gives rise to an iterative loop:

while (condition) statement

where condition is a boolean expression which evaluates to true or false. Assuming the condition is initially true the statement is repeatedly executed as long as...

UNLIMITED FREE
ACCESS
TO THE WORLD'S BEST IDEAS

SUBMIT
Already a GlobalSpec user? Log in.

This is embarrasing...

An error occurred while processing the form. Please try again in a few minutes.

Customize Your GlobalSpec Experience

Category: Flow Meters
Finish!
Privacy Policy

This is embarrasing...

An error occurred while processing the form. Please try again in a few minutes.