32 lines
633 B
C
32 lines
633 B
C
#include <assert.h>
|
||
#include <stdio.h>
|
||
#include <stdbool.h>
|
||
|
||
double approximate_pi(unsigned int steps) {
|
||
double approximate_pi = 4.0;
|
||
bool subtract = true;
|
||
|
||
/* Gregory–Leibniz series */
|
||
for (unsigned int i = 2; i <= steps; i++) {
|
||
if (subtract) {
|
||
approximate_pi -= (4.0 / (i * 2 - 1));
|
||
} else {
|
||
approximate_pi += (4.0 / (i * 2 - 1));
|
||
}
|
||
subtract = !subtract;
|
||
}
|
||
|
||
return approximate_pi;
|
||
}
|
||
|
||
int main(void) {
|
||
// printf("sizeof(int) = %d\n", sizeof(int));
|
||
|
||
double mypi = approximate_pi(100000000);
|
||
|
||
printf("pi = %8.7f\n", mypi);
|
||
assert(mypi > 3.141);
|
||
assert(mypi < 3.142);
|
||
|
||
return 0;
|
||
}
|