Gubaton Numericals

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Ernie P.

Gubaton III Activity


BSEE 4th Numerical Methods and Analysis

1. Find the positive solution of f(x)= x-2 sinx=c by the secant method starting from X1= 2
and X1= 1.5
C++ Program

#include <iostream>
#include <cmath>

using namespace std;

// Define the equation to be solved: f(x) = x - 2*sin(x) - c


double f(double x, double c) {
return x - 2 * sin(x) - c;
}

int main() {
double c = 1.0; // Change this to the desired value of c
double x0 = 2.0;
double x1 = 1.5;
double tolerance = 1e-6; // Tolerance for convergence
int maxIterations = 100; // Maximum number of iterations

for (int i = 0; i < maxIterations; i++) {


double f0 = f(x0, c);
double f1 = f(x1, c);

// Calculate the next approximation using the secant method


double x2 = x1 - f1 * ((x1 - x0) / (f1 - f0));

// Check for convergence


if (fabs(f1) < tolerance) {
cout << "Solution found: x = " << x1 << endl;
break;
}

x0 = x1;
x1 = x2;
}

return 0;
}
2. Find the positive solution of 2sinx=x
C++ Program

#include <iostream>
#include <cmath>

using namespace std;

// Define the function: f(x) = 2*sin(x) - x


double f(double x) {
return 2 * sin(x) - x;
}

// Define the derivative: f'(x) = 2*cos(x) - 1


double df(double x) {
return 2 * cos(x) - 1;
}

int main() {
double x0 = 1.0; // Initial guess for the positive solution
double tolerance = 1e-6; // Tolerance for convergence
Ernie P. Gubaton III Activity
BSEE 4th Numerical Methods and Analysis
int maxIterations = 100; // Maximum number of iterations

for (int i = 0; i < maxIterations; i++) {


double fx0 = f(x0);
double dfx0 = df(x0);

// Calculate the next approximation using the Newton-Raphson method


double x1 = x0 - fx0 / dfx0;

// Check for convergence


if (fabs(fx0) < tolerance) {
cout << "Solution found: x = " << x0 << endl;
break;
}

x0 = x1;
}

return 0;
}

3. Find a solution of f(x) x^3 + x - 1 = 0


C++ Program

#include <iostream>
#include <cmath>

using namespace std;

// Define the fixed-point iteration function: g(x) = 1 - x^3


double g(double x) {
return 1 - pow(x, 3);
}

int main() {
double x0 = 0.5; // Initial guess
double tolerance = 1e-6; // Tolerance for convergence
int maxIterations = 100; // Maximum number of iterations

for (int i = 0; i < maxIterations; i++) {


double x1 = g(x0);

// Check for convergence


if (fabs(x1 - x0) < tolerance) {
cout << "Solution found: x = " << x1 << endl;
break;
}

x0 = x1;
}

return 0;
}

You might also like