Reputation: 9
I'm trying to write a code in c to approximate the value of pi using a while loop. I know it is much easier to do so with a for loop but I'm trying to do so using while. the formula I'm using to do so is in link below: https://www.paulbui.net/wl/Taylor_Series_Pi_and_e and the code I wrote looks like this:
#include <stdio.h>
#include <math.h>
int main(){
long n=10;
while(n>0){
double a=0;
a+=((pow(-1,n))/((2*n)+1));
n=n-1;
printf("%ld",4*a);
}
return 0;
}
the reason I used long and double type is that I wanted to do the approximation to a good preciseness but first I should do st for this problem. thanks in advance.
Upvotes: 0
Views: 464
Reputation: 16540
The posted code does not cleanly compile!
gcc -ggdb3 -Wall -Wextra -Wconversion -pedantic -std=gnu11 -c "untitled.c" -o "untitled.o"
untitled.c: In function ‘main’:
untitled.c:7:19: warning: conversion from ‘long int’ to ‘double’ may change value [-Wconversion]
7 | a+=((pow(-1,n))/((2*n)+1));
| ^
untitled.c:7:22: warning: conversion from ‘long int’ to ‘double’ may change value [-Wconversion]
7 | a+=((pow(-1,n))/((2*n)+1));
| ^
untitled.c:9:17: warning: format ‘%ld’ expects argument of type ‘long int’, but argument 2 has type ‘double’ [-Wformat=]
9 | printf("%ld",4*a);
| ~~^ ~~~
| | |
| | double
| long int
| %f
Compilation finished successfully.
Note: when there are warnings, fix those warnings. Also, when there are warnings, the compiler outputs it's best guess which is not necessarily what you wanted.
Upvotes: 0
Reputation: 80187
You have to move a
initialization before loop and make stop condition - for example, evaluating current summand. Also it is worth to calculate sign incrementally without using pow
:
double a=0;
double eps= 1.0e-6; //note this series has rather slow convergence
n = 0;
double tx = 1.0;
double t = 1.0;
while(abs(tx)>eps){
tx = t / (2*n+1));
a+= tx;
printf("%f",4*a);
n++;
t = - t;
}
Upvotes: 1