Skip to content

Instantly share code, notes, and snippets.

@Techcable
Created September 13, 2018 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Techcable/53e7c92dba9f37d7ed8f91a566beaab8 to your computer and use it in GitHub Desktop.
Save Techcable/53e7c92dba9f37d7ed8f91a566beaab8 to your computer and use it in GitHub Desktop.
Euler's Method for solving Differential Equations
def parse_location(s: str):
if s.startswith("(") and s.endswith(")"):
parts = s[1:-1].split(',')
if len(parts) == 2:
try:
return tuple(map(int, parts))
except ValueError:
pass
raise ValueError(f"Invalid location: {s!r}")
def eulers_method():
equation_code = input("Differential Equation? ").strip()
equation = compile(equation_code, '<equation>', 'eval')
start = parse_location(input("Initial condition? "))
step = float(input("Approximation step? "))
end = float(input("Ending value of x? "))
def run_equation(x, y):
return eval(equation, globals(), {"x": x, "y": y})
print()
print(f"Approximating dy/dx = `{equation_code}` with initial condition {start} and step {step}")
start_derivative = run_equation(*start)
start_delta_y = start_derivative * step
table = [(start, start_derivative, start_delta_y)]
while abs(table[-1][0][0]) < abs(end):
(x_old, y_old), derivative_old, delta_y_old = table[-1]
updated_location = (x_old + step, y_old + delta_y_old)
updated_derivative = run_equation(*updated_location)
updated_delta_y = updated_derivative * step
table.append((updated_location, updated_derivative, updated_delta_y))
# Print a nice-markdown style table
print("| x | y | dy/dx | \u0394y |")
print("|-------|---------|-----------|--------|")
for (x, y), derivative, delta_y in table:
digits = 4
x = round(x, digits)
y = round(y, digits)
derivative = round(derivative, digits)
delta_y = round(delta_y, digits)
print(f"|{x: < 7}|{y: < 9}|{derivative: < 11}|{delta_y: < 8}|")
if __name__ == "__main__":
while True:
eulers_method()
if input("Do you want to continue [Y/n]?").lower() in ("no", "n"):
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment