SquareRootRandom

# SquareRootRandom - guess = rand...

This preview shows page 1. Sign up to view the full content.

/* Comptuing square roots. Author: Eric Van Wyk Date: Feb 2, 2010 */ #include <iostream> #include <cstdlib> #include <cassert> using namespace std ; int main() { double lower = 0.0, upper = 0.0, n = 0.0, accuracy = 0.0 ; double guess = 0.0 ; n = 16.0 ; accuracy = 0.001 ; lower = 1.0 ; upper = n ; int seed ; cout << "Enter the random number seed: " ; cin >> seed ; assert (cin & seed >= 0) ; srand(seed) ; // lower <= square-root(n) <= upper while ( (upper - lower) > accuracy ) { // lower <= square-root(n) <= upper // set guess to be in [0,1]
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: guess = rand() / static_cast<double>(RAND_MAX) ; // scale to range [0, (upper-lower)] guess = guess * (upper - lower) ; // move to range [lower, upper] guess = guess + lower ; cout << "Guess is " << guess << endl ; if ( guess*guess > n ) upper = guess ; else lower = guess ; } // lower <= square-root(n) <= upper // and upper - lower <= accuracy cout << "The square root of " << n << " is between " << lower << " and " << upper << "." << endl ; }...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online