# include # include # include # include # include "fsolve_tr.h" # include "trapezoidal.h" /******************************************************************************/ void trapezoidal ( void dydt ( double t, double y[], double dy[] ), double tspan[2], double y0[], int n, int m, double t[], double y[] ) /******************************************************************************/ /* Purpose: trapezoidal() uses the trapezoidal method + fsolve_be() to solve an ODE. Licensing: This code is distributed under the MIT license. Modified: 17 November 2023 Author: John Burkardt Input: dydt: a function that evaluates the right hand side of the ODE, of the form void dydt ( double t, double y[], double dy[] ) double tspan[2]: the initial and final times. double y0[m]: the initial condition. int n: the number of steps to take. int m: the number of variables. Output: double t[n+1], y[m*(n+1)]: the times and solution values. */ { double dt; double *fn; int i; int info; int j; double tn; double to; double tol; double *yn; double *yo; fn = ( double * ) malloc ( m * sizeof ( double ) ); yo = ( double * ) malloc ( m * sizeof ( double ) ); yn = ( double * ) malloc ( m * sizeof ( double ) ); dt = ( tspan[1] - tspan[0] ) / ( double ) ( n ); tol = 1.0e-05; for ( i = 0; i <= n; i++ ) { if ( i == 0 ) { t[i] = tspan[0]; for ( j = 0; j < m; j++ ) { y[i*m+j] = y0[j]; } } else { to = t[i-1]; for ( j = 0; j < m; j++ ) { yo[j] = y[(i-1)*m+j]; } tn = t[i-1] + dt; for ( j = 0; j < m; j++ ) { yn[j] = y[(i-1)*m+j]; } info = fsolve_tr ( dydt, m, to, yo, tn, yn, fn, tol ); if ( info != 1 ) { printf ( "\n" ); printf ( "trapezoidal(): Fatal error!\n" ); printf ( " info = %d\n", info ); exit ( 1 ); } t[i] = tn; for ( j = 0; j < m; j++ ) { y[i*m+j] = yn[j]; } } } free ( fn ); free ( yn ); free ( yo ); return; }