Search code examples
cwhile-looppi

Approximating the value of pi in C using Viete's Formula


My assignment this week in my CS class is create a program to approximate for pi using Viète's Formula. I've been trying to start for the past hour or so, but I'm honestly not even sure how to begin. All the work I have gotten done doesn't work.

I'm assuming my professor wants us to use the "while" loop, as we've been using it a lot in class lately. We've also been using "if" statements a lot, although I'm not sure if we need to use those here.

Can anyone help me find a starting off point or explain how I could go about doing this?

//here is some of the work i have attempted that doesn't work because i don't know what to do
#include <stdio.h> 
#include <math.h> 
#include <stdlib.h> 

int main() 

{ 
double n,pi,f,i; 

printf("enter the number of iterations to approximate for pi\n"); 
scanf("%lf\n", &n); 

pi = 2 / f; 
i = 1; 
f = sqrt(2);

while (i<=n)
{ 



}

Solution

  • To start with the code you posted:

    1) You don't want i and n to be of type double Change them to int

    2) You should always check the value returned by scanf Like: if (scanf(%d) != 1) {// add error handling here ...}

    3) pi = 2 / f; is undefined behavior as f is uninitialized

    Then your assignment:

    I'll not give you a complete solution but instead give you a hint so you can continue your work.

    The formula needed can be found here: https://en.wikipedia.org/wiki/Viète%27s_formula#Interpretation_and_convergence

    Your first task is to calculate a[n] given that

    a[1] = sqrt(2)
    a[n] = sqrt(2 + a[n-1])
    

    You can do that using a while-loop (though I would prefer a for-loop). It could be like:

    #include <stdio.h> 
    #include <math.h> 
    
    int main() 
    { 
        int n, i;
        n = 5;
        i = 1;
        double an = sqrt(2);
    
        while(i <= n)
        {
            printf("a%d = %.10f\n", i, an); 
            an = sqrt(2 + an);
            ++i;
        }
        return 0;    
    }
    

    This gives you:

    a1 = 1.4142135624
    a2 = 1.9615705608
    a3 = 1.9975909124
    a4 = 1.9998494037
    a5 = 1.9999905876
    

    So now that you know how to calculate a1, a2, a3, ... you just need to put it together using:

    enter image description here

    (image from: https://en.wikipedia.org/wiki/Viète%27s_formula#Interpretation_and_convergence)

    and find pi.