dimanche 25 septembre 2022

How am I using the formula wrong? (calculating PI with nested square roots)

I want to calculate the approx of pi with Viete's formula of nested square roots of 2

#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;
int main()
{
    int k; //variable for user input
    int n = 1; //built integer that causes the program to loop
    double result;
    //greeting message, start of program
    cout << "Welcome to the Approx PI program.\n";
    cout << "Please enter in a value for k...\n";
    cin >> k;
    //if user inputs a number outside the interval
    while (k < 1 || k > 30)
    {
        cout << "Invalid ---k must be >=1 and <=30\n";
        cout << "Please enter in a value for k...\n";
        cin >> k;
    }
    //calculating PI with the nested square root formula
    while (n <= k - 1)
    {
        result = sqrt(2 + result);
        n++;
    }
    result = pow(2, k) * sqrt(2 - result);
    //outputs the result, end of program
    cout << "Approx PI =         " <<setprecision(20)<<fixed<<result<<endl;
    return 0;
}

But when I enter 28, it gives me 4:

Welcome to the Approx PI program.
Please enter in a value for k...
28
Approx PI =         4

Process finished with exit code 0

When I enter 29 or 30, the result is 0:

Welcome to the Approx PI program.
Please enter in a value for k...
30
Approx PI =         0

Process finished with exit code 0

I think k=30 should be giving me:

Approx PI = 3.14245127249413367895

What am I doing wrong?

Aucun commentaire:

Enregistrer un commentaire