How to get the value of each integral independently in c++? - 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;
}
}

Related

Expression must have a constant value, a variable can not be used as a constant for defining array size

I am trying to produce this code but have and error in the double functions starting at double b[n];. The error I am getting is saying that "the expression must have a constant value, the variable 'n' can not be used as a constant. Any help you can give would be much appreciated.
//Get inputs from user
double V = 0; // shear load applied
int n;
double H_total = 0;
double A_total = 0;
double a = 0;
double I = 0;
double t = 0;
double e = 0;
double y_bar = 0;
cout << "Input the shear load applied in [N]: " << endl;
cin >> V;
cout << "Input number of sections: " << endl;
cin >> n;
double b[n];
double h[n];
double A[n];
double y[n];
double Q[n];
double Tau[n];
for (int i = 1; i <= n; i++) { // Calculates variables to find shear stress
cout << "Width of section " << i << " in [mm]: " << endl;
cin >> b[i];
cout << "Height of section " << i << " in [mm]: " << endl;
cin >> h[i];
H_total += h[i];
A[i] = b[i] * h[i];
A_total += A[i];
y[i] = H_total - 0.5 * h[i];
a += A[i] * y[i];
y_bar = a / A_total;
}
cout << "Applied shear force, V = " << V / 1000 << " kN" << endl;
cout << "Y coordinate of the centroid for given cross section, Y_Bar = " << y_bar << " mm" << endl;
for (int i = 1; i <= n; i++) { // Finds moment of inertia
double d = (y[i] - y_bar);
I += (b[i] * pow(h[i], 3.0) / 12.0) + (A[i] * pow(d, 2.0));
}
cout << "Moment of Inertia, I = " << I << " mm^4" << endl;
for (int i = 1; i <= n; i++) { // Calculates first moment of inertia
Q[i] = A[i] * (y[i] - y_bar);
}
for (int i = 1; i <= n - 1; i++) {
if (b[i] <= b[i + 1]) {
t = b[i];
}
else {
t = b[i + 1];
}
Tau[i] = (abs(V * Q[i]) / (I * t));
}
for (int i = 1; i <= n - 1; i++) {
if (i <= 2) {
e += Tau[i];
}
else {
e -= Tau[i];
}
cout << "Shear stress between sections " << i << " and " << i + 1 << " = " << e << " MPa" <<
endl;
}
}
First of all double b[n]; is not a function, it is an array. This error is common with 2-D arrays. However, you aren't using any 2-D arrays here. Also, your code has no error unless you provide specific inputs which cause this error.
You can see the output for some random inputs:
Applied shear force, V = 0.004 kN
Y coordinate of the centroid for given cross section, Y_Bar = 3.29661 mm
Moment of Inertia, I = 322.476 mm^4
Shear stress between sections 1 and 2 = 0.147082 MPa
Shear stress between sections 2 and 3 = 0.231598 MPa

How can I write the approximate value of PI?

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.

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

Multiplying matrices c++

I want to make a program capable of rising the 2x2 matrix to k power. I know how to make one that is going to square it but once i want to reach higher powers i struggle to save the results I have and use it in the next equation. a,b,c,d are the numbers in the matrix, n is the amount of matrix I will want to do in one time, k is the power i want the matrix to be taken to and m is modulo which I want to use on the numbers. I know there is a method of making this fairly simply but I am unable to figure out a good way to use my results from the equation done before in the next equation.
#include <iostream>
using namespace std;
int mnoz(int a, int b, int c,int d,int m){
int a2 = (a*a + c*b) % m;
int b2 = (a*b + b*d) % m;
int c2 = (c*a + d*c) % m;
int d2 = (c*b + d*d) % m;
return a2, b2, c2, d2;
}
int main()
{
int a, b, c, d, k, m, n;
int e, f, g, h;
int e2, f2, g2, h2;
cin >> n;
// a^k = (a^2)^k/2
for (int i = 0; i<n; i++){
cin >> a >> b >> c >> d >> k >> m;
if (k == 1){
cout << a << " " << b << " " << c << " " << d << endl;
}
else if (k == 2){
e = (a*a + c*b) % m;
f = (a*b + b*d) % m;
g = (c*a + d*c) % m;
h = (c*b + d*d) % m;
cout << e << " " << f << " " << g << " " << h << endl;
}
else{
if (k % 2 == 0){
e = (a*a + c*b) % m;
f = (a*b + b*d) % m;
g = (c*a + d*c) % m;
h = (c*b + d*d) % m;
int z = (k/2)-1;
for (int j = 0; j < z; j++){
int e2 = e;
int f2 = f;
int g2 = g;
int h2 = h;
mnoz(e2, f2, g2, h2, m);
}
cout << e << " " << f << " " << g << " " << h << endl;
}
}
}
system("pause");
return 0;
}
To minimize the number of multiplications, you can use a recursive method.
To give an analogy with real numbers, say you want to compute a^n.
Check whether n is even or odd.
If even, compute b = a^(n/2). Then the final result is b*b.
If odd, compute b = a^((n-1)/2. Then the final result is b*b*a.
Since you are talking matrices instead of numbers, you need to be able multiply any two matrices. You can create a class/struct for the matrix and add an operator*() function.
Here's some sample code.
#include <iostream>
struct Matrix
{
Matrix(double pa, double pb, double pc, double pd) : a(pa), b(pb), c(pc), d(pd) {}
Matrix operator*(Matrix const& rhs) const
{
double an = this->a*rhs.a + this->b*rhs.c;
double bn = this->a*rhs.b + this->b*rhs.d;
double cn = this->c*rhs.a + this->d*rhs.c;
double dn = this->c*rhs.b + this->d*rhs.d;
return Matrix(an, bn, cn, dn);
}
Matrix square() const
{
return (*this)*(*this);
}
double a;
double b;
double c;
double d;
};
Matrix matrixPower(Matrix const& m, int k)
{
if ( k == 1 )
{
return m;
}
Matrix out = matrixPower(m, k/2).square();
if ( k%2 == 1 )
{
return out*m;
}
else
{
return out;
}
}
std::ostream& operator<<(std::ostream& out, Matrix const& m)
{
out << "[ " << m.a << " " << m.b << " ]\n";
out << "[ " << m.c << " " << m.d << " ]\n";
}
int main()
{
Matrix m(0.4, 0.7, 0.7, 0.4);
std::cout << matrixPower(m, 5) << std::endl;
std::cout << matrixPower(m, 10) << std::endl;
std::cout << matrixPower(m, 15) << std::endl;
};
The output:
[ 0.80404 0.80647 ]
[ 0.80647 0.80404 ]
[ 1.29687 1.29687 ]
[ 1.29687 1.29687 ]
[ 2.08862 2.08862 ]
[ 2.08862 2.08862 ]

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