import math
from math import e
def euler(f, y0, a, b, h):
x = a
y = y0
while x + h/2 < b:
k1 = f(x,y)
x = x + h
y = y + h * k1
print ("%5.4f %5.4f" % (x,y))
def improved_euler(f, y0, a, b, h):
x = a
y = y0
while x + h/2 < b:
k1 = f(x,y)
k2 = f(x+h,y+h*k1)
x = x + h
y = y + h/2 * (k1+k2)
print ("%5.4f %5.4f" % (x,y))
def rk4(f, y0, a, b, h):
x = a
y = y0
while x + h/2 < b:
k1 = f(x,y)
k2 = f(x+h/2,y+h/2*k1)
k3 = f(x+h/2,y+h/2*k2)
k4 = f(x+h/2,y+h/2*k3)
x = x + h
y = y + h/6 * (k1+2*k2+2*k3+k4)
print ("%5.4f %5.4f" % (x,y))
def prob1(x,y):
return 2*x-3*y+1
def prob2(x,y):
return 4*x-2*y
def prob3(x,y):
return 1+y**2
def prob4(x,y):
return x**2+y**2
def prob5(x,y):
return e**-y
def prob6(x,y):
return x*y**2
def prob7(x,y):
return (x-y)**2
def prob8(x,y):
return x*y+y*.5
def prob9(x,y):
return x*y**2-y/x
def prob10(x,y):
return y-y**2
print("Problem 1 With Step .1 and .05")
rk4(prob1,5,1,1.5,.1)
rk4(prob1,5,1,1.5,.05)
print("Problem 2 With Step .1 and .05")
rk4(prob2,2,0,.5,.1)
rk4(prob2,2,0,.5,.05)
print("Problem 3 With Step .1 and .05")
rk4(prob3,0,0,.5,.1)
rk4(prob3,0,0,.5,.05)
print("Problem 4 With Step .1 and .05")
rk4(prob4,1,0,.5,.1)
rk4(prob4,1,0,.5,.05)
print("Problem 5 With Step .1 and .05")
rk4(prob5,0,0,.5,.1)
rk4(prob5,0,0,.5,0.5)
print("Problem 6 With Step .1 and .05")
rk4(prob6,0,0,.5,.1)
rk4(prob6,0,0,.5,0.5)
print("Problem 7 With Step .1 and .05")
rk4(prob7,.5,0,.5,.1)
rk4(prob7,.5,0,.5,0.5)
print("Problem 8 With Step .1 and .05")
rk4(prob8,1,0,.5,.1)
rk4(prob8,1,0,.5,0.5)
print("Problem 9 With Step .1 and .05")
rk4(prob9,1,1,1.5,.1)
rk4(prob9,1,1,1.5,0.5)
print("Problem 10 With Step .1 and .05")
rk4(prob10,.5,0,.5,.1)
rk4(prob10,.5,0,.5,0.5)
Click Run or press shift + ENTER to run code