fork download
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3.  
  4. # Define the function f(x, y) that represents the ODE
  5. def f(x, y):
  6. # Edit the equation here to represent dy/dx = f(x, y)
  7. return x**2 - y # Example: dy/dx = x^2 - y
  8.  
  9. # Euler's method implementation
  10. def euler_method(f, y0, x0, xf, h):
  11. # Number of steps
  12. num_steps = int((xf - x0) / h) + 1
  13. xs = np.linspace(x0, xf, num_steps) # x values
  14. ys = np.zeros(num_steps) # y values
  15. ys[0] = y0 # Set initial condition
  16.  
  17. # Iterative calculation using Euler's method
  18. for i in range(num_steps - 1):
  19. ys[i + 1] = ys[i] + h * f(xs[i], ys[i])
  20.  
  21. return xs, ys
  22.  
  23. # Inputs: Initial conditions and range
  24. x0 = 0 # Start value of x
  25. y0 = 1 # Initial value of y (y(x0))
  26. xf = 5 # End value of x
  27. h = 0.1 # Step size
  28.  
  29. # Solve ODE using Euler's method
  30. xs, ys = euler_method(f, y0, x0, xf, h)
  31.  
  32. # Display the solution as a list of points
  33. print("x values:", xs)
  34. print("y values:", ys)
  35.  
  36. # Plot the results
  37. plt.plot(xs, ys, marker='o', linestyle='-', color='b', label="Approximate Solution (Euler's Method)")
  38. plt.title("Euler's Method for Solving 1st Order ODE")
  39. plt.xlabel("x")
  40. plt.ylabel("y")
  41. plt.grid(True)
  42. plt.legend()
  43. plt.show()
Success #stdin #stdout 0.95s 55204KB
stdin
Standard input is empty
stdout
('x values:', array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. , 1.1, 1.2,
       1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2. , 2.1, 2.2, 2.3, 2.4, 2.5,
       2.6, 2.7, 2.8, 2.9, 3. , 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8,
       3.9, 4. , 4.1, 4.2, 4.3, 4.4, 4.5, 4.6, 4.7, 4.8, 4.9, 5. ]))
('y values:', array([ 1.        ,  0.9       ,  0.811     ,  0.7339    ,  0.66951   ,
        0.618559  ,  0.5817031 ,  0.55953279,  0.55257951,  0.56132156,
        0.5861894 ,  0.62757046,  0.68581342,  0.76123208,  0.85410887,
        0.96469798,  1.09322818,  1.23990536,  1.40491483,  1.58842335,
        1.79058101,  2.01152291,  2.25137062,  2.51023356,  2.7882102 ,
        3.08538918,  3.40185026,  3.73766524,  4.09289871,  4.46760884,
        4.86184796,  5.27566316,  5.70909685,  6.16218716,  6.63496844,
        7.1274716 ,  7.63972444,  8.171752  ,  8.7235768 ,  9.29521912,
        9.88669721, 10.49802748, 11.12922474, 11.78030226, 12.45127204,
       13.14214483, 13.85293035, 14.58363731, 15.33427358, 16.10484622,
       16.8953616 ]))