frommatplotlib.pyplotimport*frommathimport*print("Euler's Method with Slope Field")print("Enter dy/dx explicitly")print("Examples: 2*x/y, sqrt(x)*y, sin(x) - y")defget_float(prompt):whileTrue:raw=input(prompt).strip()try:returnfloat(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
ifh_raw==0:print("Step size h cannot be 0. Re-run and enter a nonzero h.")else:direction=1ifx_end>x0else-1h=abs(h_raw)*directiondefdydx(_x,_y):env={"x":_x,"y":_y,"__builtins__":{}}env.update(allowed_math)try:returneval(dydx_expression,env)exceptExceptionase:print("Error in dydx:",e)return0# Euler integration
x_vals=[x0]y_vals=[y0]whileTrue:cur_x=x_vals[-1]if (direction==1andcur_x>=x_end)or(direction==-1andcur_x<=x_end):breakstep=hif (direction==1andcur_x+step>x_end)or(direction==-1andcur_x+step<x_end):step=x_end-cur_xslope=dydx(cur_x,y_vals[-1])new_x=cur_x+stepnew_y=y_vals[-1]+step*slopex_vals.append(new_x)y_vals.append(new_y)ifnew_x==x_end:break# print table
print("\nTable of values:")print("Step\t x\t\t y")foriinrange(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:
Ensure the proper functioning of the site (essential cookies); and
Track your browsing to send you personalized communications if you have created a professional account on the site and can be contacted (audience measurement cookies).
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.