View Full Version : c code numerical methods
Im using the c programming language and just wanted to ask a quick question. In a while loop how do you make the program terminate by printing a value or a message here's my code
while ((fabs(func(x))>epsilon))
{
if(deriv(x)==0) {
print the last value of x and stop the whole program}
else {
y=(func(x)/deriv(x));
x=x-y;
printf("%d\n",iteration);
iteration=iteration+1;
printf("%lf\n",x);
}
}
Filip Larsen
Mar21-10, 09:09 AM
You can break out of a while-, for- or do-while-loop by using break. You can exit the program it the middle of everything by calling exit(0), but this is not considered good programming style.
story645
Mar21-10, 11:42 AM
You can break out of a while-, for- or do-while-loop by using break.
You can also call a return to break out of the function midway, as a function can have multiple returns.
Or you can make the exit condition part of the loop condition:
while ((fabs(func(x))>epsilon) && (deriv(x) != 0))
{
y=(func(x)/deriv(x));
x=x-y;
printf("%d\n",iteration);
iteration=iteration+1;
printf("%lf\n",x);
}
/* Now that you're out of the loop, figure out why you exited */
if (deriv(x) == 0)
{
printf ("oops, the derivative was zero!\n");
{
else
{
/* carry on normally */
}
thanks guys, i needed to use break.
When i have found my root (Program for Newton Raphson method), do you know how i can test it is accurate to a correct level of precision?, Like what kind of code would i go about writing? I used epsilon=1e-7.
If you're trying to find the root of some equation f(x) = 0 for whatever function f you're finding the root of, testing the root is easy -- just evaluate f(r), where r is your root. If |f(r)| < epsilon, you're good.
thanks Mark44,
But i was wondering, that my while loop ends when this condition is not true: (func(x))>epsilon and then displays the root x=r. So how could it be that abs(f(r))<epsilon if x=r is the root found?
What's your code look like now? I can't explain why your code is doing something if I don't see the current version of the code.
vBulletin® v3.8.7, Copyright ©2000-2012, vBulletin Solutions, Inc.