import numpy as np import matplotlib.pyplot as plt # Define the function f(x, y) that represents the ODE def f(x, y): # Edit the equation here to represent dy/dx = f(x, y) return x**2 - y # Example: dy/dx = x^2 - y # Euler's method implementation def euler_method(f, y0, x0, xf, h): # Number of steps num_steps = int((xf - x0) / h) + 1 xs = np.linspace(x0, xf, num_steps) # x values ys = np.zeros(num_steps) # y values ys[0] = y0 # Set initial condition # Iterative calculation using Euler's method for i in range(num_steps - 1): ys[i + 1] = ys[i] + h * f(xs[i], ys[i]) return xs, ys # Inputs: Initial conditions and range x0 = 0 # Start value of x y0 = 1 # Initial value of y (y(x0)) xf = 5 # End value of x h = 0.1 # Step size # Solve ODE using Euler's method xs, ys = euler_method(f, y0, x0, xf, h) # Display the solution as a list of points print("x values:", xs) print("y values:", ys) # Plot the results plt.plot(xs, ys, marker='o', linestyle='-', color='b', label="Approximate Solution (Euler's Method)") plt.title("Euler's Method for Solving 1st Order ODE") plt.xlabel("x") plt.ylabel("y") plt.grid(True) plt.legend() plt.show()
Standard input is empty
('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 ]))