eulers.py

Created by tracy-pratt-1

Created on August 19, 2025

2.04 KB


from matplotlib.pyplot import *
from math import *

print("Euler's Method with Slope Field")
print("Enter dy/dx explicitly")
print("Examples: 2*x/y, sqrt(x)*y, sin(x) - y")

def get_float(prompt):
    while True:
        raw = input(prompt).strip()
        try:
            return float(raw)
        except:
            print("Please enter a valid number (use decimal point).")

# allowed math functions for eval
allowed_math = {
    "sqrt": sqrt, "sin": sin, "cos": cos, "tan": tan,
    "log": log, "exp": exp, "pi": pi, "e": e,
    "asin": asin, "acos": acos, "atan": atan,
    "abs": abs, "pow": pow
}

# inputs
dydx_expression = input("dy/dx = ")
x0 = get_float("Initial x = ")
y0 = get_float("Initial y = ")
h_raw = get_float("Step size h = ")
x_end = get_float("End x = ")

# handle zero step and direction
if h_raw == 0:
    print("Step size h cannot be 0. Re-run and enter a nonzero h.")
else:
    direction = 1 if x_end > x0 else -1
    h = abs(h_raw) * direction

    def dydx(_x, _y):
        env = {"x": _x, "y": _y, "__builtins__": {}}
        env.update(allowed_math)
        try:
            return eval(dydx_expression, env)
        except Exception as e:
            print("Error in dydx:", e)
            return 0

    # Euler integration
    x_vals = [x0]
    y_vals = [y0]

    while True:
        cur_x = x_vals[-1]
        if (direction == 1 and cur_x >= x_end) or (direction == -1 and cur_x <= x_end):
            break
        step = h
        if (direction == 1 and cur_x + step > x_end) or (direction == -1 and cur_x + step < x_end):
            step = x_end - cur_x
        slope = dydx(cur_x, y_vals[-1])
        new_x = cur_x + step
        new_y = y_vals[-1] + step * slope
        x_vals.append(new_x)
        y_vals.append(new_y)
        if new_x == x_end:
            break

    # print table
    print("\nTable of values:")
    print("Step\t   x\t\t   y")
    for i in range(len(x_vals)):
        print(i, "\t", "%.5f" % x_vals[i], "\t", "%.5f" % y_vals[i])

    # Steps to do another
    print("Back out and Re-execute to do another")

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.