Discussion in 'C' started by jj_evans, Jun 2, 2010.

1. ### jj_evansNew Member

Joined:
Jun 2, 2010
Messages:
5
0
Trophy Points:
0
I've been trying to write the following program for a couple hours now and I'm getting frustrated. Can anyone help me?
Any help is GREATLY appreciated.

. Newton’s Method to find the square root of a non-negative number.

Let α≥0 be a number. It’s square root can be computed by Newton’s Method. That is take a rough estimate at an original value, say, . Then the following sequence gets as close to as you wish
, , , ,
ALGORITHM A non-negative number a is given
1. Define a double precision = 0.0001
2. Define doubles x0, x1 and let x0 = 0.5*a
3. Let x1 = 0.5*(x0 + a/x0)
4. As long as absolute value abs(x1 – x0) > precision LOOP
x0 = x1
x1 = 0.5*(x0 + a/x0)

5. x1 is the square root
Write a program that inputs a non-negative number and uses a while loop to implement Newton’s method given above to calculate the square root of the number and outputs the square root. Input will be from the console and output is to the console as well. Use 4 decimal places to display the result.
In addition use the predefined function sqrt to calculate the square root as well and display the result for comparison.

I know the while loop format is

while (boolean)
{statement........
satetmnt}

but I can't seem to come up with the statment. Below is what it's supposed to look like.

Joe Smith CpSc 1155 Assignment #3
Newton’s Method to compute the square root of a non-negative number
Enter a non-negative number: 5.9
Square root of 5.9 is
2.4290 using Newton’s Method with precision set to 0.0001
2.4290 using the predefined sqrt function

2. ### xpi0t0sMentor

Joined:
Aug 6, 2004
Messages:
3,009
203
Trophy Points:
63
Occupation:
Senior Support Engineer
Location:
England
Well you've pretty much been given it in part 4. Have you tried something along the lines of (untested) :
Code:
```while (abs(x1 – x0) > precision)
{
x0 = x1;
x1 = 0.5*(x0 + a/x0);
}
```

Joined:
Jun 2, 2010
Messages:
5