1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
|
#include <iomanip>
#include <iostream>
#include <windows.h>
#include <atltypes.h>
#include <vector>
typedef long F(long,long); // defines the function F as having type "double" and gives it two parameters, both of type "double"
/*
Approximates y(t) in y'(t)=f(t,y) with y(a)=y0 and
t=a..b and the step size h.
*/
long t;
long y_n;
using std::vector;
vector<POINT> Pt;
POINT pointvalues;
const POINT * pointpointer;
int counter;
long euler(F f, long y0, long a, long b, long h) // defines a class of type "void" (returns nothing); gives it parameters: function F, doubles: y0, a, b, h
{
long y_n = y0;
long t = a;
for (long t = a; t < b; t += h ) // creates a for loop beginning with time t = a and ending with t ~= b with stepsize h.
{
std::cout << std::fixed << std::setprecision(3) << t << " " << y_n << "\n"; // Calls the standard output from std, with floating-point numbers with precision 3; assigns the variable t, then a space, then variable y, then a new line.
y_n += h * f(t, y_n); // y increases by h * f(t,y) where f is the derivative y' until the condition is met y ~= b.
pointvalues.x = t*100;
pointvalues.y = y_n*100;
Pt.push_back(pointvalues);
counter++;
}
std::cout << "done\n"; // Print "done"
pointpointer = &pointvalues;
}
// Example: Newton's cooling law
long newtonCoolingLaw(long, long t) // Creates a function newtonCoolingLaw of type double with two input arguments of type double, one being the variable t.
{
return 0.07 * (t - 20); // return statement ends the function; here, it gives the time derivative y' = -0.07 * (t - 20)
}
long main() // Calls the main function with type int
{
euler(newtonCoolingLaw, 10, 0, 5, 4); // instantiation of class euler with arguments (newtonCoolingLaw, 100, 0, 100, 2)
euler(newtonCoolingLaw, 100, 0, 100, 4 ); // etc
euler(newtonCoolingLaw, 100, 0, 100, 10 ); // etc
}
|