libnum:examples:gear
Integration of Systems of Linear Differential Equations. Gear's method
Let's examine the following SLDE:
y₁′ = y₂ y₂′ = y₁ y₁(0)=0 and y₂(0)=1
NB: we expect sin(x)/cos(x) as the result.
#include <iostream>
#include <sstream>
#include <fstream>
#include <math.h>
#include "libnum/gear.h"
#include "libnum/gear.output.h"
using namespace NumericMethods;
/*
y₁′ = y₂
y₂′ = y₁
y₁(0)=0 and y₂(0)=1
// NB: we expect sin(x)/cos(x) as the result.
*/
static bool derfun(int n, double x, const double y[], double dy[])
{
dy[0] = y[1];
dy[1] = -y[0];
return true;
}
static bool jacobian(int n, double x, const double y[], double j[])
{
//for (int i = 0; i<n*n; ++i) j[i] = 0;
j[0] = 0; j[1] = 1; j[2] = -1; j[3] = 0; // sin/cos
return true;
}
int main()
{
double initValues[]={ 0,1,0,0};
GearUserProc uf1(derfun),uf2(jacobian);
Gear solver;
solver.set(2,&uf1,&uf2);
GearAssistant& assistant = solver.assistant;
assistant.params.setParameter("HINI", 0.000001); // starting step of integration
assistant.params.setParameter("EPS", 0.0001); // step error constant
// Output variants
/*1*/ GearPrintToStream print_1(std::cout, "{:8.5f}\t");
/*2*/ std::stringstream buf; // to string; use buf.str() later
GearPrintToStream print_2(buf, "{:8.5f}\t");
/*3*/ std::ofstream file("gear_output.txt");
GearPrintToStream print_3(file, "{:8.5f}\t");
GearPrintTable print_4(std::cout, 0.1);
print_4.setFormat("{:8.5f}\t");
solver.setCallback(print_4);
try
{
Message rc=solver.solve(0, 5, initValues);
}
catch(Message& e)
{
std::cout << "\n\n" << e.getMessageID().data();
}
std::cout << "\n";
}
[ Libnum methods ]
libnum/examples/gear.txt · Last modified: by abc
