Trying to solve this Second Order ODE in both excel and C++ using Heun\'s Method
ID: 3770845 • Letter: T
Question
Trying to solve this Second Order ODE in both excel and C++ using Heun's Method:
Write a C++ program and excel spreadsheet using the shooting method in combination with Heun's Method that can solve the following Boundary-Value Second Order Differential Equation: y'' + 4y' + 4y = 0, with y(0)=0 and y(1)=3.
The program must prompt the user to provide a first guess of the slope at x = 0. You can select any step size you consider reasonable; proof of solution will be decided on how well the calculated results match the analytical solution at x=1.
The analytical solution is: y = 3xe^(-2x+2)
Explanation / Answer
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
long double f(long double x11, long double y11) {
return ((3 * exp(0.15*x11)) - (0.15*y11));
}
long double g(long double x11) {
return (4/1.3)*(exp(0.15*x11)-exp(-0.15*x11))+2*exp(-0.15*x11);
}
long double hf0(long double x12, long double y12, long double h1) {
return y12 + (f(x12, y12) * h1);
}
long double hf0_corrector(long double x12, long double y12, long double x21, long double y22, long double h1) {
return y12 + (((f(x12, y12) + f(x21, y22)) / 2)*h1);
}
long double get_error(long double a11, long double b11) {
return abs(((a11-b11)*100/a11));
}
int main(int argc, char** argv) {
cout << fixed;
cout << setprecision (60);
long double x01 = 0;
long double y01 = 2;
long double step = 1e-3;
long double x_mx = 4;
long double pred = 0;
long double targeterror = 2e-5;
long double err = 100;
long double correctornew = 0;
unsigned long int i11 = 0;
long double ytrue;
long double etrue = 100;
long double etrue_now = 100;
long double corre;
long double true_maxerror = 0;
for (x01= 0; x01<=x_mx; x01=x01+step) {
targeterror = 2e-5;
err = 100;
etrue = 100;
etrue_now = 101;
correctornew = 0;
i11 = 0;
ytrue = g(x01 + step);
pred = hf0(x01, y01, step);
corre = hf0_corrector(x01, y01, (x01 + step), pred, step);
while (etrue > 1) {
correctornew = hf0_corrector(x01, y01, (x01 + step), corre, step);
err = get_error(corre, correctornew);
etrue_now = get_error(corre, ytrue);
corre = correctornew;
i11++;
if (etrue_now == etrue) break;
etrue = etrue_now;
}
if (true_maxerror < etrue) {
true_maxerror = etrue;
}
y01= corre;
}
cout << "at f(" << x01 << "): " << endl;
cout << "estd y: " << corre << endl;
return 0;
}