Question

Well, I have a problems with a specific C code. I'm dealing with solving a task without using any "refined" coding, that is, doing regular stuff with the simplest of the libraries and functions. Particulary, I am ONLY allowed to use stdio.h , not any library more. And no strings, also.

The problem: I have to do the cosine of a real number x (stored in double), which is given by the user, using this expression: cos (x) = ((x^(2i))/((2i)!))*(-1)^i, all this inside a sumatore from i = 0 to i = n, being n the precision (an int number) which the user chooses. Ok, I've managed to do this code so far:

        scanf("%lf", &x);
        r1 = x;
        scanf("%d", &n);
        for (i = 0; i <= n; i++){
            for(cont1 = 0; cont1 < 2*i; cont1++){
                r1 = r1*r1;
            }
            for(cont2 = 1; cont2 <= 2*i; cont2++){
                r2 = r2*cont2;
            }
            for(cont3 = 1; cont3 < i; cont3++){
                r3 = (-1)*(-1);
            }
            result = result + (r1/r2)*r3;
        }
        printf("The result is %lf\n", result);

But the output is always 1.#INF00, all the time. Does anybody know why this happens? Could somebody tell me how to manage to get the right code? It would be very appreciated.

Thank you in advance.

Was it helpful?

Solution

Incorrect term calculation.
Term variables are not re-initialize each loop, which appears to be OP's algorithm's need.

[Edit] Code

double MyCosine(double Angle, int Terms) {
  int cont1, cont2, cont3;
  double r1, r2, r3;
  // r1 = Angle;
  int i, n = Terms;
  double result = 0.0;
  for (i = 0; i <= n; i++) {
    r1 = 1.0;
    for (cont1 = 0; cont1 < 2 * i; cont1++) {
      // r1 = r1 * r1;
      r1 = r1 * Angle;
    }
    r2 = 1.0;
    for (cont2 = 1; cont2 <= 2 * i; cont2++) {
      r2 = r2 * cont2;
    }
    r3 = 1;
    // for (cont3 = 1; cont3 < i; cont3++) {
    for (cont3 = 0; cont3 < i; cont3++) {
      // r3 = (-1) * (-1);
      r3 = r3 * (-1);
    }
    result = result + (r1 / r2) * r3;
  }
  printf("%e %e\n", result, cos(Angle));
  return result;
}

A re-write would not need to re-initialize the term and then the nested for loops could be eliminated. Other simplification exists.

OTHER TIPS

When you compute the terms x^(2i) / (2i)!, you can't compute x^(2i) and (2i)! separately and then divide, as both of them will grow larger than the largest number that fits in a double very quickly. Therefore you are running into infs and similar problems.

You need to find a clever more robust way to calculate these terms (which is probably the point of this assignment).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top