Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What do I need to do to get the correct value o PI?

Greeting.
I am doing the following exercise: Run a program to determine an approximate value of π using the series shown below. The calculation is performed by generating a certain number of terms in the series. The number of terms to be considered is read from the standard input (keyboard) (greater than or equal to 30000).
Note: In the resolution of this issue, you cannot use functions from the math.h library of the C programming language.

enter image description here
example: input a value enter total terms >=30000: entering 30000 should give you the result o pi:3.141559
The prolem I’m having: Uppon entering the same value(30000)I am not getting the corret value o pi=3.14…. but instead it’s something like:0.0067…

heres my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include<stdio.h>
#include<math.h>
int main(void){
    double numerator, denominator, pi=0.0;
    int k;
    printf("input a total number o terms >=30000:");
    for ( k=1;k<=30000;k++){
         scanf("%d",&k);

         if(k>=30000){
    
             if(k%2==0){
                 numerator=1;   
             }
             else {
                  numerator=-1;
             }
          }
          denominator=2.0*k+1.0;
          pi+=numerator/denominator;
          pi=4*pi;
          printf("value of PI is= %lf",pi);
    }
return 0;
}

Can someone point out what I am doing wrong and how can I solve it pls?

Your time and attention are deeply appreciated.

Thank You.

>Solution :

There are many problems with what your implementation of the algorithm:

Try avoiding scanf ad printf inside the for loop.

Instead of getting the k variable from the user try and get the maximum value of k.

denominator=2*k+1 is wrong if you follow the algorithm that you gave in your question and should be changed to denominator=2*k-1.

You repeat pi*=4 every iteration.

I applied all those improvement and i get pi=3.141926 for just 3000 iterations.

Here a little help on how your for loop should look like:

for (int k=1;k<iterations;k++){
      numerator*=-1;
      denominator=2.0*k-1.0;
      pi+=numerator/denominator;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading