105 lines
2.1 KiB
C
105 lines
2.1 KiB
C
/* Name: Garrett Haldrup
|
|
pi.c
|
|
Problem: Experiments with different methods of calculating pi, and sees how close they get to the real thing
|
|
Certification of Authenticity:
|
|
I certify that this assignment is entirely my own work.
|
|
*/
|
|
|
|
#include <stdio.h>
|
|
#include <math.h>
|
|
|
|
double piWallis(int n);
|
|
double piGregory(int n);
|
|
double piNilakantha(int n);
|
|
double piEuler(int n);
|
|
void piCompare(double pi);
|
|
|
|
|
|
int main() {
|
|
|
|
int n;
|
|
double pi;
|
|
|
|
printf("Enter the number of n iterations to do\nfor each method of calculating pi: ");
|
|
scanf("%d", &n);
|
|
|
|
pi = piWallis(n);
|
|
piCompare(pi);
|
|
pi = piGregory(n);
|
|
piCompare(pi);
|
|
pi = piNilakantha(n);
|
|
piCompare(pi);
|
|
pi = piEuler(n);
|
|
piCompare(pi);
|
|
}
|
|
|
|
double piWallis(int n) {
|
|
int top = 0;
|
|
int bottom = 1;
|
|
double pi = 1;
|
|
|
|
printf("\nThis will calculate pi using the Wallis Method.\n");
|
|
|
|
for (int i = 0; i < n; i++) {
|
|
top += ((i + 1) % 2) * 2;
|
|
bottom += (i % 2) * 2;
|
|
pi *= (float)top / (float)bottom;
|
|
}
|
|
pi *= 2;
|
|
printf("The %d of pi is: %lf\n",n ,pi);
|
|
return pi;
|
|
}
|
|
|
|
double piGregory(int n) {
|
|
int top = 4;
|
|
int bottom = 1;
|
|
double pi = 0;
|
|
|
|
printf("\nThis will calculate pi using the Gregory Method.\n");
|
|
|
|
for (int i = 0; i < n; i++) {
|
|
bottom = (1 + (2 * i)) * pow(-1, i);
|
|
pi += (float)top / (float)bottom;
|
|
}
|
|
printf("The %d of pi is: %lf\n",n ,pi);
|
|
return pi;
|
|
}
|
|
|
|
double piNilakantha(int n) {
|
|
int top = 4;
|
|
int bottom;
|
|
double pi = 3;
|
|
|
|
printf("\nThis will calculate pi using the Nilakantha Method.\n");
|
|
|
|
for (int i = 1; i < n; i++) {
|
|
bottom = (2*i) * (2*i+1) * (2*i+2) * pow(-1, i - 1);
|
|
pi += (float)top / (float) bottom;
|
|
}
|
|
|
|
printf("The %d of pi is: %lf\n",n ,pi);
|
|
return pi;
|
|
}
|
|
|
|
double piEuler(int n) {
|
|
int bottom;
|
|
double pi = 0;
|
|
|
|
printf("\nThis will calculate pi using the Euler Method.\n");
|
|
|
|
for (int i = 0; i < n; i++) {
|
|
bottom = pow(i+1,2);
|
|
pi += 1.0 / bottom;
|
|
}
|
|
pi = sqrt(6 * pi);
|
|
printf("The %d of pi is: %lf\n",n ,pi);
|
|
return pi;
|
|
}
|
|
|
|
void piCompare(double pi) {
|
|
double diff;
|
|
|
|
diff = M_PI - pi;
|
|
printf("The difference from the actual value of pi is: %lf\n", diff);
|
|
}
|