i just started on C and i tried to convert my working PI approximation JS code to C But when compiling my C it doesn't approximate correctly...
I think it's because i'm not using double variables at the right way.
Here's my code:
#include <iostream>
using namespace std;
double four = 4, pi = 4, num = 1;
bool lever = false;
int calcpi() {
while (true) {
num = num 2;
if (lever) {
lever = false;
pi = (four/num) - pi;
} else if(lever == false){
lever = true;
pi = (four/num) pi;
}
cout << pi <<"\n";
}
}
int main(){
calcpi();
}
CodePudding user response:
It looks like you're implementing the approximation
π = 4 – 4/3 4/5 – 4/7 4/9 – …
In that case, the line pi = (four/num) - pi;
is backwards. It should be pi = pi - (four/num);
, which represents the subtraction terms.
Also, subtraction from the initial value of 4 should be the first operation, so the lever
flag should be initialized to true
.
Here's the modified version that I got working after a little bit of troubleshooting.
void calcpi() {
double pi = 4.0, num = 1.0;
bool lever = true;
for (int i = 0; i < 1000; i ) {
num = num 2.0;
if (lever) {
lever = false;
pi = pi - (4.0 / num);
}
else {
lever = true;
pi = pi (4.0 / num);
}
std::cout << pi << std::endl;
}
}
This does give a slowly converging approximation of Pi.
CodePudding user response:
This should work:
#include <iostream>
using namespace std;
// changed values of constant and variable
// to comply with the mathematical formula:
// pi = 4 * (0 1/1 - 1/3 1/5 - 1/7 ...)
// four = 4 was changed to one = 1, because
// we use it as our numerator, which is always 1
// pi = 4 was changed to pi = 0 (first element
// of our infinite series)
// num = 1 was changed to num = -1 (at the
// beginning of the while loop, before we
// manipulate pi, we add 2 to num, so
// -1 2 = 1 <- first value of our denominator
double one = 1, pi = 0, num = -1;
bool lever = false;
void calcpi() { // void instead of int, because this function doesn't return anything
while (true) {
num = 2; // I prefer x = y instead of x = x y, doesn't really matter
if (lever) {
lever = false;
pi -= (one / num); // negative elements of the infinite series
} else if(lever == false){ // this is redundant: we know lever == false at this point
lever = true;
pi = (one / num); // positive elements of the infinite series
}
cout << 4 * pi << '\n'; // our variable 'pi' is actually pi/4
}
}
int main() {
calcpi();
}
I assumed you use the Leibniz formula for π and I tried not to modify your code too much, but be wary - it's quite wonky.
If I were to write something similar, it'd look something like this:
#include <iostream>
void calcpi(int iter) {
double pi = 0, denom = 1;
bool lever = false;
for (int i = 0; i < iter; i ) {
if (lever) {
lever = false;
pi -= (1 / denom);
} else {
lever = true;
pi = (1 / denom);
}
denom = 2;
std::cout << 4 * pi << '\n';
}
}
int main() {
calcpi(426200); // should be enough given the default cout precision
return 0;
}