hey all. im working on a homework script so PLEASE do not give me exact code, just direction and explanations. Thank you.
I have a working bit of code that calculates the square root, yes i know there is a math.h that will do that, but this is the homework.
It properly calculates the root to 0.005, but it never stops. the loop just keeps going for ever. My issue is the updating of the variables. im a bit stuck. here is the code and ill explain what i want to happen, what is happening, and where im confused.
Code:
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
#include<math.h>
int main(void)
{
double N, NG, LG, *PLG, epsilon, root; // setting all variables to type double
epsilon = 0.005; // setting error tolerance to 0.005
LG = 1.0; // setting initial guess value
printf("\nPlease enter the number you wish to find the square root: ");
scanf("%lf",&N); // getting input from user
do {
NG = 0.5 * (LG + (N / LG));
printf("%.2lf %.3lf\n", N, NG);
LG = NG;
} while (fabs(NG - LG) < epsilon);
printf("\nThe square root of %.2lf is %.3lf\n", N, NG);
}
This works but never stops.
NG = next guess
LG = last guess with the initial value for the guess set to 1.
the formula NG = 0.5 * (LG + (N / LG)) works just fine. both on paper and in the computer.
My issue comes with making the result of NG become the new LG if the epsilon is not met:
NG - LG < 0.005 if this is false then set LG to the value calculated of NG, wash and repeat. This is the part im confused on. How to accomplish this section.
looking at
http://www.cygnus-software.com/paper...ringfloats.htm
i read the following:
Quote:
Comparing with epsilon – absolute error
Since floating point calculations involve a bit of uncertainty we can try to allow for this by seeing if two numbers are ‘close’ to each other. If you decide – based on error analysis, testing, or a wild guess – that the result should always be within 0.00001 of the expected result then you can change your comparison to this:
if (fabs(result - expectedResult) < 0.00001)
The maximum error value is typically called epsilon.
|
i was just useing the following:
NG - LG <= epsilon this did not function the way i wanted either. Again i think it has to do with how to make LG the value of the results to the NG formula.
Thanks in advance from lost, dazed, and confused.