PI number calculating with c++ program [duplicate] - c++

This question already has an answer here:
Dividing two integers to produce a float result [duplicate]
(1 answer)
Closed 2 years ago.
// PI = 4 - (4/3) + (4/5) - (4/7) ... for 100 first statements
#include <iostream>
#include <conio.h>
using namespace std;
int main() {
double PI = 0.0;
int a = 1;
for (int i = 1; i <= 100; i++) {
if (i % 2 == 1) {
PI += double(4 / a);
}
else {
PI -= double(4 / a);
}
a += 2;
}
cout << "PI Number is : " << PI;
cout << endl;
return 0;
}
I tried this code in visual studio 2015 to give me the answer of PI number value but it returns "PI Number is : 3" and I want it to return a float or a double number.
What should I do?

In double(4 / a), the 4 / a part evaluates to an integer and it is already truncated by the time you cast it to double. What you want to do is 4.0 / a instead, and no need for an explicit cast.

4 / a is an integer division and your conversion double(…) happens after that division, so the result will never have something after the decimal point. e.g. 4/5 results in 0.
You need to change 4 from an integer to a double 4.

The issue in your code is when it's computing the value:
double PI = 0.0;
int a = 1;
for (int i = 1; i <= 100; i++) {
if (i % 2 == 1) {
PI += double(4 / a);
}
else {
PI -= double(4 / a);
}
a += 2;
}
You shouldn't do double(4 / a) but rather (double)4 / a or 4.0 / a
double PI = 0.0;
int a = 1;
for (int i = 1; i <= 100; i++) {
if (i % 2 == 1) {
PI += (double)4 / a;
}
else {
PI -= (double)4 / a;
}
a += 2;
}

Related

Algorithm to calculate n digits of pi in C++?

Here's what I have:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double pi = 0;
long i;
long n;
cout << "Enter the value of n: ";
cin >> n;
cout << endl;
for (i = 0; i < n; i++)
{
if (i % 2 == 0)
pi = pi + (1 / (2 * i + 1));
else
pi = pi - (1 / (2 * i + 1));
pi = 4 * pi;
}
cout << endl << "pi = " << pi << endl;
return 0;
}
However, this does not give the desired output. For example, n = 9, pi = 262144. I know it's possible to just store pi as a constant and get the result that way, but I'm wondering what I am doing wrong using the algorithm above.
Because of long i;, (1 / (2 * i + 1)) will be zero for any i>0.
When i=0, you got pi=1;
for i=1,9, you got pi = 4*pi;
That's why you got 262144 which is 4^8.
You might want
for (i = 0; i < n; i++)
{
if (i % 2 == 0)
pi = pi + (1.0 / (2 * i + 1));
else
pi = pi - (1.0 / (2 * i + 1));
}
pi = 4 * pi;

PI Approximation not approximating right

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

How do I fix this bug with arctanx function in c++

I've recently been given a problem by my teacher about some mathematical equation / formula called the arctanx formula. The question is:
According to the Arctanx(x) = x - ((x ^ 3) / 3) + ((x ^ 5) / 5) - ((x ^
7) / 7) + ...and π = 6 * arctanx(1 / sqrt(3)), Create function arctanx(x)
, and find pi when the last "number"(like this ((x ^ y) / y)) is right before
and bigger than 10 ^ -6, or you can say that no "number" can be smaller than
that number without being smaller than 10 ^ -6.
I tried to code it out, but there is a bug in it.
# include<iostream>
# include<math.h>
using namespace std;
float arctanx() {
long double pi = 3.1415926535897;
int i = 0; // 0 = +, 1 = -
float sum = 0;
float lsum;
for (int y = 1; y < pi; y += 2) {
if (lsum > 0.000001) {
if (i == 0) {
lsum = pow(1 / sqrt(3), y) / y;
sum += pow(1 / sqrt(3), y) / y;
i++;
} else if (i == 1) {
lsum = pow(1 / sqrt(3), y) / y;
sum -= pow(1 / sqrt(3), y) / y;
i--;
}
} else {
break;
}
}
sum = sum * 6;
return sum;
}
int main() {
cout << arctanx();
return 0;
}
It should have a output of some number not equal to zero, but I got 0 from running this.
Your program has Undefined Behavior because you are using the uninitialized float lsum; in the comparison if (lsum > 0.000001).
What probably happens in your case is that lsum happens to be less than or equal to 0.000001 and your for immediately breaks without doing anything causing your function to return 0 * 6 which is obviously 0.
Create function arctanx(x)
The function defined in the posted code doesn't accept any parameter, it just uses the hardwired (and repeated) value 1 / sqrt(3) and tries to return an approximated value of π instead of the arctangent of x.
It also has undefined behavior, beeing lsum uninitialized (therefore having an indeterminate value) when it is first used in the comparison inside the loop.
Consider this implementation, but be advised that this particular polinomial expansion diverges for values of x greater than 1.
#include <iostream>
#include <iomanip>
#include <cmath>
double arctanx(double x);
int main()
{
double pi = 6.0 * arctanx(1.0 / std::sqrt(3));
std::cout << std::setprecision(8) << pi << '\n';
}
double arctanx(double x)
{
// You can take advantage of a running power, instad of calculating
// pow(x, i) at every iteration
double sq_x = x * x;
double pow_x = x * sq_x;
double err = 1e-6;
// Instead of keeping track of the alternating sign, you can use
// two separate partial sums
double sum_pos_term = x;
double sum_neg_term = 0.0;
for (int i = 3; i < 33; i += 2) // <- Limit the number of iterations
{
if (pow_x < err * i)
break;
sum_neg_term += pow_x / i;
i += 2;
pow_x *= sq_x;
if (pow_x < err * i)
break;
sum_pos_term += pow_x / i;
pow_x *= sq_x;
}
return sum_pos_term - sum_neg_term;
}

Summation of a series [duplicate]

This question already has an answer here:
Dividing two integers to produce a float result [duplicate]
(1 answer)
Closed 4 years ago.
This is my code and i'm trying to calculate this series : ((-1)^n)*n/(n+1) that n started from 1 to 5, code is not working correctly, anyone can help ?
int main(){
int i,n;
double sum1;
for (i=1; i<6; i++)
sum1 += (pow(-1,i))*((i)/(i+1));
cout<<sum1;
return 0;
}
The true answer at the end must be equal to -0.6166666666666667 which code cant calculate it correctly.
I calculated series from here. Is there any special function to do summation ?
Make sure to initialize your variables before you use them. You initialize i afterwards so it's fine like this, but sum1 needs to be initialized:
double sum1 = 0.0;
For the summation, even if the result is assigned to a double, the intermediate results might not be and integer devision result in truncated values. For this reason, double literals should be used (such as 2.0 instead of 2) and i should be casted where applicable:
sum1 += (pow(-1, i))*(((double)i) / ((double)i + 1.0));
Finally, to get the desired precision, std::setprecision can be used in the print. The final result could look like this:
int main() {
int i;
double sum1 = 0.0;
for (i = 1; i < 6; i++)
sum1 += (pow(-1, i))*(((double)i) / ((double)i + 1.0));
std::cout << std::setprecision(15) << sum1 << std::endl;
return 0;
}
Output:
-0.616666666666667
Always init variables before usage. double sum1 = 0;
((i) / (i + 1)) performs integer division, the result is 0 for any i.
Use for the pow function to find power of -1 is extremely irrational
int main() {
int i;
double sum1 = 0;
double sign = -1;
for (i = 1; i < 6; i++)
{
sum1 += sign * i / (i + 1);
sign *= -1.0;
}
std::cout << sum1;
return 0;
}
Try this instead
for (i = 0; i <= 5; i++) // from 0 to 5 inclusively
sum1 += (pow(-1, i)) * (static_cast<double>(i) / (i + 1));

How would I code this basic C++ program more cleanly, to run more efficiently or to return a more precise figure?

It is supposed to evaluate e^pi - pi.
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
long double Pie();
long double Factorial(double n);
long double E();
int main()
{
long double answer = pow(E(),Pie()) - Pie();
cout << setprecision(20);
cout << answer;
return 0;
}
long double Pie()
{
long double a = 1;
long double b = (1 / sqrtl(2));
long double t = (1.0 / 4.0);
long double p = 1;
long double aPlaceholder;
for (int i = 1; i < 5; i++)
{
aPlaceholder = a;
a = (a + b) / 2;
b = sqrtl(aPlaceholder * b);
t = t - p * (aPlaceholder - a) * (aPlaceholder - a);
p = 2 * p;
}
long double nicePie;
nicePie = (a + b) * (a + b) / (4 * t);
return nicePie;
}
long double E()
{
long double e = 0;
for(double i = 0; i < 20; i++)
e += 1.0 / Factorial(i);
return e;
}
long double Factorial(double n)
{
if(n == 0)
return 1;
int i = n - 1;
while (i > 0)
{
n *= i;
i--;
}
return n;
}
The scenario is that I want to evaluate e, raise it to the power of pi, and then subtract pi from the result and then print the answer to the screen. Another aspect to the scenario is that this is a basic C++ program.
<cmath> provides double long exp(double long): http://www.cplusplus.com/reference/clibrary/cmath/exp/ as well as the Pi constant M_PI in double precision.
Boost provides Pi in long double precision :
const long double pi = boost::math::constants::pi<long double>();
That being said there is some calculus in your code that you do multiple times while it is not needed:
Pie is called twice.
In E(), Factorial is called at every iteration while you could multiply the previous result with i.
.
long double E()
{
long double e = 0;
long double fact_i = 1;
for(double i = 1; i < 20; i++)
{
fact_i *= i;
e += 1.0 / fact_i;
}
return e;
}
cmath provides π and e as predefined constants as M_PI and M_E accurate within the precision of double, but it's not mandatory by C++ standard.
You can just do double pi = acos(-1);