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();
}
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.