Search code examples
c++pi

How do I fix this bug with arctanx function in c++


I've recently been given a problem by my teacher about some mathematical equation / formula called the arctanx formula. The question is:

According to the Arctanx(x) = x - ((x ^ 3) / 3) + ((x ^ 5) / 5) - ((x ^ 
7) / 7) + ...and π = 6 * arctanx(1 / sqrt(3)), Create function arctanx(x)
, and find pi when the last "number"(like this ((x ^ y) / y)) is right before
 and bigger than 10 ^ -6, or you can say that no "number" can be smaller than
that number without being smaller than 10 ^ -6.

I tried to code it out, but there is a bug in it.

# include<iostream>
# include<math.h>
using namespace std;
float arctanx() {
    long double pi = 3.1415926535897;
    int i = 0; // 0 = +, 1 = -
    float sum = 0;
    float lsum;
    for (int y = 1; y < pi; y += 2) {
        if (lsum > 0.000001) {
            if (i == 0) {
                lsum = pow(1 / sqrt(3), y) / y;
                sum += pow(1 / sqrt(3), y) / y;
                i++;
            } else if (i == 1) {
                lsum = pow(1 / sqrt(3), y) / y;
                sum -= pow(1 / sqrt(3), y) / y;
                i--;
            }
        } else {
            break;
        }
    }

    sum = sum * 6;
    return sum;

}

int main() {
    cout << arctanx();
    return 0;
}

It should have a output of some number not equal to zero, but I got 0 from running this.


Solution

  • Your program has Undefined Behavior because you are using the uninitialized float lsum; in the comparison if (lsum > 0.000001). What probably happens in your case is that lsum happens to be less than or equal to 0.000001 and your for immediately breaks without doing anything causing your function to return 0 * 6 which is obviously 0.