Runge-Kutta method: Difference between revisions
→{{header|C++}}: simplifying a bit
(Added Wren) |
(→{{header|C++}}: simplifying a bit) |
||
Line 408:
Using Lambdas
<lang cpp>/*
* compiled with
* g++
*
* g++ -std=c++14 -o rk4 %
*
*/
# include <iostream>
# include <math.h>
auto rk4(double f(double, double))
{
return
[
[
[
[
[
( dy1 + 2*dy2 + 2*dy3 + dy4 ) / 6 ;} (
dt * f( t+dt , y+dy3 ) );} (
Line 429 ⟶ 430:
dt * f( t+dt/2, y+dy1/2 ) );} (
dt * f( t , y ) );} ;
}
bool is_whole(double t) {
constexpr double WHOLE_TOLERANCE = 1e-12;
return std::fabs(t-round(t)) < WHOLE_TOLERANCE;
}
int main(void)
{
auto eval_diff_eqn = [ ](double t, double y)->double{ return t*sqrt(y) ; } ;▼
for (
▲ double y = Y_START, t = T_START ;
double y = Y_START, t = T_START ;
if (is_whole(t))
return 0;
▲ while(t <= TIME_MAXIMUM) {
▲ if (is_whole(t)) { printf("y(%4.1f)\t=%12.6f \t error: %12.6e\n",t,y,find_error(t,y)); }
▲ y += dy(t,y,DT) ; t += DT;
▲ }
▲ return 0;
}</lang>
|