How can I write the approximate value of PI? - c++

the code works but the result keeps getting bigger whenever i put 2 or a higher value in it
#include <iostream>
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;
}

Because your { and } is wrong. I think brackets will be as given below
If the formula is PI = 4/1 - 4/3 + 4/5 - 4/7 + ... ( Leibniz's Series ) then you can formalate as given below
#include <iostream>
using namespace std;
int main() {
double n, i; // Number of iterations and control variable
double s = 1; //Signal for the next iteration
double pi = 0.0;
cout << "Enter the value of n: ";
cin >> n;
cout << endl;
cout << "Approximation of the number PI through the Leibniz's series\n";
for(i = 1; i <= (n * 2); i += 2){
pi = pi + s * (4 / i);
s = -s;
cout << "Step (" << (i-1)/2 << "):" << pi << endl;
}
cout << endl << "pi = " << pi << endl;
return 0;
}
Then result will be as if n = 13
Approximation of the number PI through the Leibniz's series
Step (0):4
Step (1):2.66667
Step (2):3.46667
Step (3):2.89524
Step (4):3.33968
Step (5):2.97605
Step (6):3.28374
Step (7):3.01707
Step (8):3.25237
Step (9):3.04184
Step (10):3.23232
Step (11):3.0584
Step (12):3.2184
pi = 3.2184

For Wallis's Series found in Europe by John Wallis in 1655 ( PI = 2/1 x 2/3 x 4/3 x 4/5 x ....) then code will be as
#include <iostream>
using namespace std;
int main()
{
double n, i = 0 ; // Number of iterations and control variable
double pi = 4.;
cout << "Approximation of the number pi through the Wallis's series\n";
cin >> n;
cout << endl;
for(i = 3; i <= (n + 2); i+=2) {
pi = pi * ((i - 1) / i) * (( i + 1) / i);
cout << "Step(" << (i-3)/2 << "):" << pi << endl;
}
cout << "\nAproximated value of PI = " << pi << endl;
}
then result will be
Approximation of the number pi through the Wallis's series
Step(0):3.55556
Step(1):3.41333
Step(2):3.34367
Step(3):3.30239
Step(4):3.2751
Step(5):3.25572
Step(6):3.24125
Step(7):3.23004
Step(8):3.22109
Step(9):3.21378
Step(10):3.20771
Step(11):3.20258
Step(12):3.19818
Step(13):3.19438
Step(14):3.19106
Step(15):3.18813
Step(16):3.18552
Step(17):3.1832
Step(18):3.1811
Step(19):3.17921
Aproximated value of PI = 3.17921

For Nilakantha's Series PI = 3 + 4/(2x3x4) - 4/(4x5x6) + 4/(6x7x8) - ... then code will be as given
#include <iostream>
using namespace std;
int main()
{
double n, i; // Number of iterations and control variable
double s = 1; //Signal for the next operation
double pi = 3;
cout << "Approximation of the number PI through the sequence of the Nilakantha's series\n" ;
cin >> n;
cout << endl;
for(i = 2; i <= n*2; i += 2){
pi = pi + s * (4 / (i * (i + 1) * (i + 2)));
s = -s;
cout << "Step(" << (i-2)/2 << "):" << pi << endl;
}
cout << "\nAproximated value of PI = " << pi << endl;
}
Then result will be as
Approximation of the number PI through the sequence of the Nilakantha's series
Step(0):3.16667
Step(1):3.13333
Step(2):3.14524
Step(3):3.13968
Step(4):3.14271
Step(5):3.14088
Step(6):3.14207
Step(7):3.14125
Step(8):3.14184
Step(9):3.14141
Step(10):3.14174
Step(11):3.14148
Step(12):3.14168
Step(13):3.14152
Step(14):3.14165
Step(15):3.14154
Step(16):3.14164
Step(17):3.14156
Step(18):3.14162
Step(19):3.14157
Aproximated value of PI = 3.14157

Another implementation of the Leibniz's Series:
double pi = 0.0;
double first_denominator = 1.0;
double second_denominator = 3.0;
for (i = 0; i < N; ++i)
{
pi += 4.0 / first_denominator;
pi -= 4.0 / second_denominator;
first_denominator += 2;
second_denominator += 2;
}
By adding in pairs of terms, the need to switch signs has been removed.

Related

How to get the value of each integral independently in c++?

I am using simpson's 1/3 rule in c++ to find the integral of k*(x*x), where k=2*m and 'm' goes from 1 to 10, hence I have 10 integrals. When I wrote the code below I got the answers but its adding the values of integral from the previous ones! e.g. for m=1 => k=2 the integral is 0.66667, now for m=2 => k=4 instead of getting 0.33333, the integral is 2.00 (0.66667+0.33333). How to prevent it from doing that?
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
int k;
double f(double x) {
return k * pow(x, 2);
}
int main() {
int n = 100000, m;
double h, a = 0, b = 1, sum = 0, x, y;
cout << "The number of sub-intervals is n = " << n << endl;
cout << fixed << showpoint << setprecision(5);
for (m = 1; m <= 10; m++) {
cout << "m = " << m << endl;
k = 2 * m;
cout << "k = " << k << endl;
h = (b - a) / n;
for (int i = 1; i <= n; i++) {
x = a + i * h;
if (i % 2 == 0) {
sum = sum + 2 * f(x);
} else {
sum = sum + 4 * f(x);
}
}
y = h / 3.0 * (f(a) + sum + f(b));
cout << "The integration is: " << y << endl;
}
}

Stack around the array is corrupted

I am using Visual Studios 2015, and I ran into a problem. Run-Time Check Failure #2 - Stack around the variable 'myArray' was corrupted. I am not sure where in the program that could cause some sort of corruption to my array. But when I did calculations involving manipulating the array, several numbers turned to 0.0000 instead of what they were originally. Could someone help?
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
double xmin, xmax;
const int POINTS = 20;
const double PI = 3.1416;
double increments;
double range, mean;
double total = 0;
double myArray[POINTS];
double number = myArray[0];
double mode = number;
int count = 1;
int countMode = 1;
cout << "Enter in a value for the minimum x value: ";
cin >> xmin;
cout << "Enter in a value for the maximum x value: ";
cin >> xmax;
if (xmin < 0)
increments = (abs(xmin) + xmax) / POINTS;
else
increments = (xmax - xmin) / POINTS;
int i = 0;
double x = xmin + increments * i;
double minimum = 0.0572 * cos(4.667 * x) + 0.0218 * PI * cos(12.22 * x);
double maximum = myArray[19];
cout << setw(15) << "x |" << setw(15) << "f(x)" << endl;
cout << setw(32) << setfill('-') << " " << endl;
cout << setfill(' ');
for (i = 0; i <= POINTS; i++)
{
myArray[i] = 0.0572 * cos(4.667 * x) + 0.0218 * PI * cos(12.22 * x);
x = xmin + increments * i;
cout << fixed << showpos << setw(15) << setprecision(2) << x << setw(15) << setprecision(4) << myArray[i] << endl;
if (myArray[i] <= minimum)
minimum = myArray[i];
if (myArray[i] > maximum)
maximum = myArray[i];
}
cout << endl;
range = maximum - minimum;
for (int count = 0; count <= POINTS; count++)
{
total += myArray[count];
}
mean = total / POINTS;
int temp;
bool swap;
do
{
swap = false;
for (int i = 0; i < POINTS - 1; i++)
{
if (myArray[i] > myArray[i + 1])
{
temp = myArray[i];
myArray[i] = myArray[i + 1];
myArray[i + 1] = temp;
swap = true;
}
}
} while (swap);
for (int i = 0; i <= POINTS; i++)
{
if (myArray[i] == number)
{
count++;
}
else
{
if (count > countMode)
{
countMode = count;
mode = number;
}
count = 1;
number = myArray[i];
}
}
cout << "The maximum value is: " << maximum << endl;
cout << "The minimum value is: " << minimum << endl;
cout << "The range is: " << range << endl;
cout << "The mean value is: " << mean << endl;
cout << "The median value is: " << (myArray[9] + myArray[10]) / 2 << endl;
cout << "The mode value is: " << mode << endl;
for (i = 0; i <= POINTS; i++)
cout << myArray[i] << endl;
system("pause");
return 0;
}
double myArray[POINTS];
myArray is an array of 20 doubles - myArray[0] through myArray[19].
for (i = 0; i <= POINTS; i++)
{
myArray[i] = 0.0572 * cos(4.667 * x) + 0.0218 * PI * cos(12.22 * x);
This sets myArray[0] through myArray[20]. Accessing myArray[20] is a not allowed, because that is the 21st element of a 20-element array.
Note that the compiler won't always be nice enough to detect this problem for you. Visual C++ is doing you a favour here by causing the program to crash, believe it or not.

Formatting the output of a C++ program

I have already written most of the code for the problem and it works. I'm just unsure of how to format the output.
Problem : Design and develop a C++ program for Calculating e(n) when delta <= 0.000001
e(n-1) = 1 + 1/1! + 1/2! + 1/3! + 1/4! + … + 1/(n-1)!
e(n) = 1 + 1/1! + 1/2! + 1/3! + 1/4! + … + 1/(n)!
delta = e(n) – e(n-1)
You do not have any input to the program. Your output should be something like this:
N = 2 e(1) = 2 e(2) = 2.5 delta = 0.5
N = 3 e(2) = 2.5 e(3) = 2.565 delta = 0.065
#include <iostream>
using namespace std;
//3! = 3 * 2!
//2! = 2 * 1!
//1! = 1
int factorial(int number)
{
//if number is <= 1, return 1
if (number <= 1)
{
return 1;
}
// otherwise multiply number by factorial(number - 1)
else
{
//otherwise multiply number by factorial(number - 1) and return it
int temp = number * factorial(number - 1);
cout << "factorial of " << number << " = " << temp << endl;
return temp;
}
}
double sumOfFactorials(int n)
{
double sum = 0;
//loop from 1..n, adding the factorial division to a sum
for (int i = 1; i <= n; i++)
{
double dividedValue = 1.00000 / factorial(i);
cout << fixed;
sum = sum + dividedValue;
}
return sum;
}
/**
* Compute the sum of 1 + ... + 1/(n!)
* input number: 1
* output number: 1 + ... + 1/(input!)
*/
double e(int n)
{
double value = 1 + sumOfFactorials(n);
return value;
}
int main()
{
cout << "e:" << e(3) << endl; // 1 + sumOfFactorials(3)
cout << "sumOfFactorials: " << sumOfFactorials(3) << endl; //0 + 1/1! + 1/2! + 1/3!
}
You have the right code, All you need is to format the output. Just modify the main() method. here is a snippet you can try.
NOTE : There is an error in the precision of the answer, I think you can correct it.
PS : Please uncomment your debugging cout lines.
int main()
{
for(int i = 2; i<4; i++){
double en_1 = e(i-1);
double en = e(i);
double delta = en - en_1;
cout << "N = "<<i;
cout << " e("<< (i-1) <<") = " << en_1;
cout << " e("<< (i) <<") = " << en;
cout << "delta = " << delta;
cout << "\n";
}
}

My c++ code for factoring isn't working

I am trying to create a c++ program that when I input two numbers (num1, combinationNum), it finds two numbers that multiply together to equal num1, but add together to equal combinationNum. It currently works for positive integers, but not negative. How do I make it work with negative integers? Also, If the equation isn't solvable, I would like it to print an error of some sort. Thanks!
Code:
//
// main.cpp
// Factor
//
// Created by Dani Smith on 2/13/14.
// Copyright (c) 2014 Dani Smith Productions. All rights reserved.
//
#include <iostream>
#include <cmath>
using namespace std;
void factors(int num, int comNum){
int a, b;
cout<<"The factors are ";
bool isPrime = true;
int root = (int)sqrt((double)num);
for(int i = 2; i <= root; i++){
if(num % i == 0 ){
isPrime = false;
//cout<<i<<",";
for(int x = 0; x<3; x++){
if(x==1){
a = i;
}
else if(x == 2){
b = i;
}
if(a + b == comNum){
cout << a << ", and " << b << ".";
}
}
}
}
//----------------------------------------
if(isPrime)cout<<"1 ";
cout<<endl;
}
int main(int argc, const char * argv[])
{
int num1 = 0, num2 = 0, multiple = 0, combinationNum = 0, output1 = 0, output2 = 0;
cout << "What number do you want to factor?\n";
cin >> num1;
cout << "What do you want them to add to?\n";
cin >> combinationNum;
factors(num1, combinationNum);
return 0;
}
To solve:
x + y == a
x * y == b
You have to solve
y == a - x
x * x - a * x + b == 0
So with delta == a * a - 4 * b, if delta positive, the solutions are
x1 = (a + sqrt(delta)) / 2
x2 = (a + sqrt(delta)) / 2
The code : (https://ideone.com/qwrSwa)
void solve(int sum, int mul)
{
std::cout << "solution for x + y = " << sum << std::endl
<< " x * y = " << mul << std::endl;
const int delta = sum * sum - 4 * mul;
if (delta < 0) {
std::cout << "No solution" << std::endl;
return;
}
const float sqrtdelta = sqrtf(delta);
const float x1 = (sum + sqrtdelta) / 2.f;
const float x2 = (sum - sqrtdelta) / 2.f;
std::cout << "x = " << x1 << ", y = " << sum - x1 << std::endl;
if (delta != 0) {
std::cout << "x = " << x2 << ", y = " << sum - x2 << std::endl;
}
}

Compute tan(x) to be infinity in C++

#include <iostream>
#include <math.h>
#include <cstdlib>
using namespace std;
double cosin_value( double value );
double sin_value( double value );
double big_degree( double value );
double big_radian( double value );
double x;
double value;
double degree;
double radian;
const double PI = 3.14159;
char choice;
char yes;
int main()
{
cout << "Please enter an angle value => ";
cin >> value;
cout << "Is the angle in Degree or Radian?" << endl;
cout << "\t" << "Type D if it is in Degree" << endl;
cout << "\t" << "Type R if it is in Radian" << endl;
cout << "Your response => ";
cin >> choice; //degree or radian?
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(10);
if (choice == 'D' || choice == 'd')
{
big_degree (value);
cout << " " << "sin(x) = " << "\t" << sin_value(degree) << endl;
cout << " " << "cos(x) = " << "\t" << cosin_value(degree) << endl;
cout << " " << "tan(x) = " << "\t" << sin_value(degree) / cosin_value(degree) << endl;
}
else if (choice == 'R' || choice == 'r')
{
big_radian (value);
cout << " " << "sin(x) = " << "\t" << sin_value(radian) << endl;
cout << " " << "cos(x) = " << "\t" << cosin_value(radian) << endl;
cout << " " << "tan(x) = " << "\t" << sin_value(radian) / cosin_value(radian) << endl;
}
return 0;
}
// Sine,cosine functions
// angle -360<value<360
double sin_value( double value )
{
int count=1;
double sine, num, dem, sign, term;
sine = 0;
sign = 1;
num = value;
dem = count;
while ( count <= 20 )
{
term = ( num / dem );
sine = sine + term * sign;
num = num * value * value;
count = count + 2;
dem = dem * count * ( count - 1 );
sign = -sign;
}
return (sine);
}
double cosin_value( double value )
{
int count = 0;
double cosine, num, dem, sign, term;
cosine = 0;
sign = 1;
num = 1;
dem = 1;
while ( count <= 20 )
{
term = ( num / dem );
cosine = cosine + term * sign;
num = num * value * value;
count = count + 2;
dem = dem * count * ( count - 1 );
sign = -sign;
}
return (cosine);
}
double big_degree( double value )
{
int result;
const int angle = 360;
if (value >= 360 || value <= -360)
{
result = value / angle;
degree = ( value - ( result * angle ) ) * PI / 180;
}
else
{
degree = ( value * PI ) / 180;
}
return (degree);
}
double big_radian( double value )
{
int result;
if (value >= 2 * PI || value <= -2 * PI)
{
result = value / ( 2 * PI );
radian = ( value - ( result* 2 * PI ) );
}
else
{
radian = value;
}
return (radian);
}
I have few problems here:
How can the program shows tan(x) is infinity when I input a value 90 degree or 1.5708 radian? When I input 90 degree, it gave me an output of 0.0000013268 instead of 0 for cos(x).
I tried to put in this command in my cosin function where If cos(x)<0.00001, set it to zero, it worked for 90 degree but for other values like 2.3145 radian, cos(x) value is 0 instead of -0.677013.
I appreciate your guides!
Use epsilon value just like you mentioned in question #2.
Use an absolute value of cos(x) like abs(cos(x)) in your if statement. .
You can also represent infinity with double or float. Check this link.
http://www.gnu.org/software/libc/manual/html_node/Infinity-and-NaN.html
More importantly, you might want to read this article called "What Every Computer Scientist Should Know About Floating-Point Arithmetic"
http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
You will notice that each step of your floating point operations will accumulate errors in calculation.