Thread: Cosine fucntion and infinite loop.

  1. #1
    Registered User
    Join Date
    Oct 2008

    Cosine fucntion and infinite loop.

    im not to sure what is going on here, when i compile my program and run it, the thing works fine for values below 2 and above -2. beyond those limits my program seems to go into an infinite loop.......

    /* fucntion that computes the cosine of angle X */ 
    #include "trig.h"
    #include "util.h"
    #include <stdio.h>
            /* Function that computes the value of cosine for a given float value passed in. */
            double cos(float angle_x)
                    /* Variable decleration */
                    double sign = -1;
                    int n = 2;
                    double old, result = 1;
                    /* This saves the current with the old results */
                    old = result;
                    /* computes the cosine using its taylor series */
                    result = result + sign* ((double)pos_power(angle_x, n)) / (double)factorial(n);
                    /* switches '+' to '-' */
                    sign *= -1;
                    /* counting for increments of power in pos_power and factorial value in factorial() */
                    n = n + 2;
            /* while loop runs as long as the error is smaller then absolute value of variable old & results (old-results) */
            while(!close_enough(old, result));
            /* returns the last result of the while do function */
            return result;
    ill include my driver and all files needed to run the program and hopefully someone can explain to me whats happening.

  2. #2
    Registered User
    Join Date
    Oct 2008
    oops forgot the files.

  3. #3
    The larch
    Join Date
    May 2006
    The problem appears to be with the factorials. The algorithm may need factorials that are too large for the int type. You might try using unsigned long long (or perhaps double?).
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed