fork download
  1.  
  2. #include <stdio.h>
  3. #include <math.h>
  4.  
  5. // Define the ODE function: dy/dx = 3y - 12y^2
  6. double f(double x, double y) {
  7. return 3 * y - 12 * y * y;
  8. }
  9.  
  10. // Runge-Kutta 4th order method to generate initial values
  11. void runge_kutta_4(double (*f)(double, double), double y0, double x0, double xf, double h, double *x_values, double *y_values, int n) {
  12. double x = x0;
  13. double y = y0;
  14. for (int i = 0; i < n; i++) {
  15. x_values[i] = x;
  16. y_values[i] = y;
  17.  
  18. double k1 = h * f(x, y);
  19. double k2 = h * f(x + 0.5 * h, y + 0.5 * k1);
  20. double k3 = h * f(x + 0.5 * h, y + 0.5 * k2);
  21. double k4 = h * f(x + h, y + k3);
  22.  
  23. y = y + (1.0 / 6.0) * (k1 + 2 * k2 + 2 * k3 + k4);
  24. x = x + h;
  25. }
  26. }
  27.  
  28. // Adams-Bashforth 2-step method for prediction
  29. void adams_bashforth_2(double (*f)(double, double), double *x_values, double *y_values, double h, int n) {
  30. for (int i = 2; i < n; i++) {
  31. double f1 = f(x_values[i-1], y_values[i-1]);
  32. double f2 = f(x_values[i-2], y_values[i-2]);
  33.  
  34. y_values[i] = y_values[i-1] + (h / 2) * (3 * f1 - f2);
  35. }
  36. }
  37.  
  38. int main() {
  39. // Initial conditions
  40. double y0 = 0.2; // initial value of y
  41. double x0 = 0; // initial value of x
  42. double xf = 2.0; // final value of x
  43. double h = 0.1; // step size
  44. int n = (int)((xf - x0) / h) + 1; // number of steps
  45.  
  46. // Arrays to store x and y values
  47. double x_values[n], y_values[n];
  48.  
  49. // Step 1: Use Runge-Kutta to generate initial values
  50. runge_kutta_4(f, y0, x0, xf, h, x_values, y_values, n);
  51.  
  52. // Step 2: Apply Adams-Bashforth 2-step method to predict further values
  53. adams_bashforth_2(f, x_values, y_values, h, n);
  54.  
  55. // Print the results (x, y)
  56. printf("x\t\ty\n");
  57. for (int i = 0; i < n; i++) {
  58. printf("%.2f\t%.6f\n", x_values[i], y_values[i]);
  59. }
  60.  
  61. return 0;
  62. }
  63.  
Success #stdin #stdout #stderr 0.26s 40876KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected '/' in "/"
Execution halted