Cosine fucntion and infinite loop.

This is a discussion on Cosine fucntion and infinite loop. within the C Programming forums, part of the General Programming Boards category; im not to sure what is going on here, when i compile my program and run it, the thing works ...

  1. #1
    Registered User
    Join Date
    Oct 2008
    Posts
    17

    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.......

    Code:
    /* 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;
            do
            {
                    /* 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
    Posts
    17
    oops forgot the files.
    Attached Files Attached Files

  3. #3
    The larch
    Join Date
    May 2006
    Posts
    3,573
    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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21