C code numerical methods

  • Thread starter jam12
  • Start date
  • #1
38
0

Main Question or Discussion Point

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);

}

}
 
Last edited:

Answers and Replies

  • #2
Filip Larsen
Gold Member
1,256
183
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.
 
  • #3
673
2
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.
 
  • #4
jtbell
Mentor
15,544
3,453
Or you can make the exit condition part of the loop condition:

Code:
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 */
}
 
  • #5
38
0
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.
 
Last edited:
  • #6
33,494
5,186
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.
 
  • #7
38
0
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?
 
Last edited:
  • #8
33,494
5,186
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.
 

Related Threads on C code numerical methods

  • Last Post
Replies
14
Views
3K
  • Last Post
Replies
1
Views
3K
  • Last Post
Replies
0
Views
5K
Replies
28
Views
5K
  • Last Post
Replies
6
Views
921
  • Last Post
Replies
1
Views
15K
  • Last Post
Replies
9
Views
10K
Replies
4
Views
1K
Replies
6
Views
629
Top