Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C code numerical methods

  1. Mar 21, 2010 #1
    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: Mar 21, 2010
  2. jcsd
  3. Mar 21, 2010 #2

    Filip Larsen

    User Avatar
    Gold Member

    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.
     
  4. Mar 21, 2010 #3
    You can also call a return to break out of the function midway, as a function can have multiple returns.
     
  5. Mar 21, 2010 #4

    jtbell

    User Avatar

    Staff: Mentor

    Or you can make the exit condition part of the loop condition:

    Code (Text):

    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 */
    }
     
     
  6. Mar 24, 2010 #5
    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: Mar 24, 2010
  7. Mar 24, 2010 #6

    Mark44

    Staff: Mentor

    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.
     
  8. Mar 24, 2010 #7
    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: Mar 24, 2010
  9. Mar 24, 2010 #8

    Mark44

    Staff: Mentor

    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.
     
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook