Esempio n. 1
0
def Fig1(): 
# Figure #1 in the Lab: The solution of y'=y-2x+4, y(0)=0, is 
# y(x) = -2 + 2x + (ya + 2)e^x. This code plots the solution for 0<x<2,
# and then plots the approximation given by Euler's method
# Text Example
	a, b, ya = 0.0, 2.0, 0.0
	def f(x,ya=0.): 
		return -2. + 2.*x + (ya + 2.)*np.exp(x)
	
	def ode_f(x,y): 
		return np.array([1.*y -2.*x + 4.])
	
	
	plt.plot(np.linspace(a,b,11), euler(ode_f,ya,a,b,11) , 'b-',label="h = 0.2")
	plt.plot(np.linspace(a,b,21), euler(ode_f,ya,a,b,21) , 'g-',label="h = 0.1")
	plt.plot(np.linspace(a,b,41), euler(ode_f,ya,a,b,41) , 'r-',label="h = 0.05")
	
	x = np.linspace(0,2,200); k =int(200/40)
	plt.plot(x[::k], f(x[::k]), 'k*-',label="Solution") # The solution
	plt.plot(x[k-1::k], f(x[k-1::k]), 'k-') # The solution
	
	plt.legend(loc='best')
	plt.xlabel('x'); plt.ylabel('y')
	# plt.savefig('Fig1.pdf')
	plt.show()
	plt.clf()
	return
Esempio n. 2
0
def problem_euler():
    # Figure #2 in the Lab: The solution of y'=y-2x+4, y(0)=0, is
    # y(x) = -2 + 2x + (ya + 2)e^x. This code plots the solution for 0<x<2,
    # and then plots the approximation given by Euler's method
    # Text Example
    a, b, ya = 0.0, 2.0, 0.0

    def f(x, ya=0.0):
        return -2.0 + 2.0 * x + (ya + 2.0) * np.exp(x)

    def ode_f(x, y):
        return np.array([1.0 * y - 2.0 * x + 4.0])

    plt.plot(np.linspace(a, b, 11), euler(ode_f, ya, a, b, 11), "b-", label="h = 0.2")
    plt.plot(np.linspace(a, b, 21), euler(ode_f, ya, a, b, 21), "g-", label="h = 0.1")
    plt.plot(np.linspace(a, b, 41), euler(ode_f, ya, a, b, 41), "r-", label="h = 0.05")

    x = np.linspace(0, 2, 200)
    k = int(200 / 40)
    plt.plot(x[::k], f(x[::k]), "k*-", label="Solution")  # The solution
    plt.plot(x[k - 1 :: k], f(x[k - 1 :: k]), "k-")  # The solution

    plt.legend(loc="best")
    plt.xlabel("x")
    plt.ylabel("y")
    # plt.savefig('prob1.pdf')
    plt.show()
    plt.clf()
    return
Esempio n. 3
0
def Exercise1():
    a, b, ya = 0.0, 2.0, 0.0

    def f(x, ya=0.):
        return 4. - 2. * x + (ya - 4.) * np.exp(-x)

    def ode_f(x, y):
        return np.array([-1. * y - 2. * x + 2.])

    plt.plot(np.linspace(a, b, 11),
             euler(ode_f, ya, a, b, 11),
             'b-',
             label="h = 0.2")
    plt.plot(np.linspace(a, b, 21),
             euler(ode_f, ya, a, b, 21),
             'g-',
             label="h = 0.1")
    plt.plot(np.linspace(a, b, 41),
             euler(ode_f, ya, a, b, 41),
             'r-',
             label="h = 0.05")

    x = np.linspace(0, 2, 200)
    k = int(200 / 40)
    plt.plot(x[::k], f(x[::k]), 'k*-', label="Solution")  # The solution
    plt.plot(x[k - 1::k], f(x[k - 1::k]), 'k-')  # The solution

    plt.legend(loc='best')
    plt.xlabel('x')
    plt.ylabel('y')
    # plt.savefig('Exercise1.pdf')
    plt.show()
    plt.clf()
Esempio n. 4
0
def problem_relative_error():
    # Figure 3 in the lab.
    a, b, ya = 0.0, 2.0, 0.0

    def f(x, ya):
        return -2.0 + 2.0 * x + 2.0 * np.exp(x)

    def ode_f(x, y):
        return np.array([1.0 * y - 2.0 * x + 4.0])

    N = np.array([10, 20, 40, 80, 160])  # Number of subintervals
    Euler_sol, Mid_sol, RK4_sol = np.zeros(len(N)), np.zeros(len(N)), np.zeros(len(N))
    for j in range(len(N)):
        Euler_sol[j] = euler(ode_f, ya, a, b, N[j])[-1]
        Mid_sol[j] = midpoint(ode_f, ya, a, b, N[j])[-1]
        RK4_sol[j] = RK4(ode_f, ya, a, b, N[j])[-1]

    h = 2.0 / N
    plt.loglog(h, abs((Euler_sol - f(2.0, 0.0)) / f(2.0, 0.0)), "-b", label="Euler method", linewidth=2.0)
    plt.loglog(h, abs((Mid_sol - f(2.0, 0.0)) / f(2.0, 0.0)), "-g", label="Midpoint method", linewidth=2.0)
    plt.loglog(h, abs((RK4_sol - f(2.0, 0.0)) / f(2.0, 0.0)), "-k", label="Runge Kutta 4", linewidth=2.0)
    plt.xlabel("$h$", fontsize=16)
    plt.ylabel("Relative Error", fontsize=16)
    # plt.title("loglog plot of relative error in approximation of $y(2)$.")
    plt.legend(loc="best")
    # plt.savefig('relative_error.pdf')
    plt.show()
    plt.clf()
Esempio n. 5
0
def Fig3():
    a, b, ya = 0., 2., 0.
    def f(x,ya):
        return -2. + 2.*x + 2.*np.exp(x)
    
    def ode_f(x,y): 
        return np.array([1.*y -2.*x + 4.])
    
    N = np.array([10,20,40,80,160])  # Number of subintervals
    Euler_sol, Mid_sol, RK4_sol = np.zeros(len(N)), np.zeros(len(N)), np.zeros(len(N))
    for j in range(len(N)):
            Euler_sol[j] = euler(ode_f,ya,a,b,N[j])[-1]
            Mid_sol[j] = midpoint(ode_f,ya,a,b,N[j])[-1]
            RK4_sol[j] = RK4(ode_f,ya,a,b,N[j])[-1]
    
    h = 2./N
    plt.loglog(h, abs(( Euler_sol - f(2.,0.))/f(2.,0.) ), '-b', label="Euler method"   , linewidth=2.)
    plt.loglog(h, abs(( Mid_sol - f(2.,0.))/f(2.,0.) ),   '-g', label="Midpoint method", linewidth=2. )
    plt.loglog(h, abs(( RK4_sol - f(2.,0.))/f(2.,0.) ),   '-k', label="Runge Kutta 4"  , linewidth=2. )
    plt.xlabel("$h$", fontsize=16)
    plt.ylabel("Relative Error", fontsize = 16)
    # plt.title("loglog plot of relative error in approximation of $y(2)$.")
    plt.legend(loc='best')
    # plt.savefig('Fig3.pdf')
    plt.show()
    plt.clf()
Esempio n. 6
0
def Fig4():
    a, b, ya = 0., 8., 1.
    from math import exp, sin, cos

    def f(x):
        return exp(sin(x))

    def ode_f(x, y):
        return np.array([y * cos(x)])

    # Number of subintervals
    N1 = np.array([
        10, 20, 40, 80, 160, 320, 640, 1280, 2560, 5120, 10240, 20480, 40960,
        81920, 163840, 327680, 655360, 1310720
    ])
    N2, N3 = N1[:12], N1[:10]
    Euler_sol, Mid_sol, RK4_sol = np.zeros(len(N1)), np.zeros(
        len(N2)), np.zeros(len(N3))

    for j in range(len(N1)):
        Euler_sol[j] = euler(ode_f, ya, a, b, N1[j])[-1]
    for j in range(len(N2)):
        Mid_sol[j] = midpoint(ode_f, ya, a, b, N2[j])[-1]
    for j in range(len(N3)):
        RK4_sol[j] = RK4(ode_f, ya, a, b, N3[j])[-1]

    # Data for a Table?
    euler_error = np.concatenate((abs(
        (Euler_sol - f(b)) / f(b))[:, np.newaxis], N1[:, np.newaxis]),
                                 axis=1)
    rk4_error = np.concatenate((abs(
        (RK4_sol - f(b)) / f(b))[:, np.newaxis], 4 * N3[:, np.newaxis]),
                               axis=1)

    # Plot number of function evaluations versus relative error
    fig = plt.figure()
    plt.loglog(N1,
               abs((Euler_sol - f(b)) / f(b)),
               '-b',
               label="Euler method",
               linewidth=2.)
    plt.loglog(2 * N2,
               abs((Mid_sol - f(b)) / f(b)),
               '-g',
               label="Midpoint method",
               linewidth=2.)
    plt.loglog(4 * N3,
               abs((RK4_sol - f(b)) / f(b)),
               '-k',
               label="Runge Kutta 4",
               linewidth=2.)
    ax = fig.add_subplot(111)
    plt.ylabel("Error", fontsize=16)
    plt.xlabel("Functional Evaluations", fontsize=16)
    ax.legend(loc='best')
    # ax.invert_xaxis()
    # plt.savefig('Fig4.pdf')
    plt.show()
    plt.clf()
Esempio n. 7
0
def example_relative_error():
    # Figure 3 in the lab.
    a, b, ya = 0., 2., 0.

    def ode_f(x, y):
        return np.array([1. * y - 2. * x + 4.])

    best_grid = 320  #  number of subintervals in most refined grid
    best_val = euler(ode_f, ya, a, b, best_grid)[-1]
    smaller_grids = [10, 20, 40, 80]  # number of subintervals in smaller grids
    h = [2. / N for N in smaller_grids]
    Euler_sol = [euler(ode_f, ya, a, b, N)[-1] for N in smaller_grids]
    Euler_error = [abs((val - best_val) / best_val) for val in Euler_sol]

    plt.loglog(h, Euler_error, '-b', label="Euler method", linewidth=2.)
    # plt.xlabel("$h$", fontsize=16)
    # plt.ylabel("Relative Error", fontsize = 16)
    # plt.legend(loc='best')
    plt.show()
    plt.clf()
Esempio n. 8
0
def example_relative_error():
    # Figure 3 in the lab.
    a, b, ya = 0.0, 2.0, 0.0

    def ode_f(x, y):
        return np.array([1.0 * y - 2.0 * x + 4.0])

    best_grid = 320  #  number of subintervals in most refined grid
    best_val = euler(ode_f, ya, a, b, best_grid)[-1]
    smaller_grids = [10, 20, 40, 80]  # number of subintervals in smaller grids
    h = [2.0 / N for N in smaller_grids]
    Euler_sol = [euler(ode_f, ya, a, b, N)[-1] for N in smaller_grids]
    Euler_error = [abs((val - best_val) / best_val) for val in Euler_sol]

    plt.loglog(h, Euler_error, "-b", label="Euler method", linewidth=2.0)
    # plt.xlabel("$h$", fontsize=16)
    # plt.ylabel("Relative Error", fontsize = 16)
    # plt.legend(loc='best')
    plt.show()
    plt.clf()
Esempio n. 9
0
def Exercise1(): 
	a, b, ya = 0.0, 2.0, 0.0
	def f(x,ya=0.): 
		return 4. - 2.*x + (ya - 4.)*np.exp(-x)
	
	def ode_f(x,y): 
		return np.array([-1.*y -2.*x + 2.])
	
	
	plt.plot(np.linspace(a,b,11), euler(ode_f,ya,a,b,11) , 'b-',label="h = 0.2")
	plt.plot(np.linspace(a,b,21), euler(ode_f,ya,a,b,21) , 'g-',label="h = 0.1")
	plt.plot(np.linspace(a,b,41), euler(ode_f,ya,a,b,41) , 'r-',label="h = 0.05")
	
	x = np.linspace(0,2,200); k =int(200/40)
	plt.plot(x[::k], f(x[::k]), 'k*-',label="Solution") # The solution 
	plt.plot(x[k-1::k], f(x[k-1::k]), 'k-') # The solution 
	
	plt.legend(loc='best')
	plt.xlabel('x'); plt.ylabel('y')
	# plt.savefig('Exercise1.pdf')
	plt.show()
	plt.clf()
Esempio n. 10
0
def problem_euler():
    # Figure #2 in the Lab: The solution of y'=y-2x+4, y(0)=0, is
    # y(x) = -2 + 2x + (ya + 2)e^x. This code plots the solution for 0<x<2,
    # and then plots the approximation given by Euler's method
    # Text Example
    a, b, ya = 0.0, 2.0, 0.0

    def f(x, ya=0.):
        return -2. + 2. * x + (ya + 2.) * np.exp(x)

    def ode_f(x, y):
        return np.array([1. * y - 2. * x + 4.])

    plt.plot(np.linspace(a, b, 11),
             euler(ode_f, ya, a, b, 11),
             'b-',
             label="h = 0.2")
    plt.plot(np.linspace(a, b, 21),
             euler(ode_f, ya, a, b, 21),
             'g-',
             label="h = 0.1")
    plt.plot(np.linspace(a, b, 41),
             euler(ode_f, ya, a, b, 41),
             'r-',
             label="h = 0.05")

    x = np.linspace(0, 2, 200)
    k = int(200 / 40)
    plt.plot(x[::k], f(x[::k]), 'k*-', label="Solution")  # The solution
    plt.plot(x[k - 1::k], f(x[k - 1::k]), 'k-')  # The solution

    plt.legend(loc='best')
    plt.xlabel('x')
    plt.ylabel('y')
    # plt.savefig('prob1.pdf')
    plt.show()
    plt.clf()
    return
Esempio n. 11
0
def Exercise3():
    a, b, ya = 0., 2., 0.

    def f(x, ya):
        return 4. - 2. * x + (ya - 4.) * np.exp(-x)

    def ode_f(x, y):
        return np.array([-1. * y - 2. * x + 2.])

    N = np.array([10, 20, 40, 80, 160])  # Number of subintervals
    Euler_sol, Mid_sol, RK4_sol = np.zeros(len(N)), np.zeros(len(N)), np.zeros(
        len(N))
    for j in range(len(N)):
        Euler_sol[j] = euler(ode_f, ya, a, b, N[j])[-1]
        Mid_sol[j] = midpoint(ode_f, ya, a, b, N[j])[-1]
        RK4_sol[j] = RK4(ode_f, ya, a, b, N[j])[-1]

    # print Euler_sol, Mid_sol, RK4_sol
    # print "Answer = ", f(2.,0.)
    h = 2. / N
    plt.loglog(h,
               abs((Euler_sol - f(2., 0.)) / f(2., 0.)),
               '-b',
               label="Euler method",
               linewidth=2.)
    plt.loglog(h,
               abs((Mid_sol - f(2., 0.)) / f(2., 0.)),
               '-g',
               label="Midpoint method",
               linewidth=2.)
    plt.loglog(h,
               abs((RK4_sol - f(2., 0.)) / f(2., 0.)),
               '-k',
               label="Runge Kutta 4",
               linewidth=2.)
    plt.xlabel("$h$", fontsize=16)
    plt.ylabel("Relative Error", fontsize=16)
    plt.title("loglog plot of relative error in approximation of $y(2)$.")
    plt.legend(loc='best')
    # plt.savefig("Exercise3.pdf")
    # plt.show()
    plt.clf()
Esempio n. 12
0
def problem_relative_error():
    # Figure 3 in the lab.
    a, b, ya = 0., 2., 0.

    def f(x, ya):
        return -2. + 2. * x + 2. * np.exp(x)

    def ode_f(x, y):
        return np.array([1. * y - 2. * x + 4.])

    N = np.array([10, 20, 40, 80, 160])  # Number of subintervals
    Euler_sol, Mid_sol, RK4_sol = np.zeros(len(N)), np.zeros(len(N)), np.zeros(
        len(N))
    for j in range(len(N)):
        Euler_sol[j] = euler(ode_f, ya, a, b, N[j])[-1]
        Mid_sol[j] = midpoint(ode_f, ya, a, b, N[j])[-1]
        RK4_sol[j] = RK4(ode_f, ya, a, b, N[j])[-1]

    h = 2. / N
    plt.loglog(h,
               abs((Euler_sol - f(2., 0.)) / f(2., 0.)),
               '-b',
               label="Euler method",
               linewidth=2.)
    plt.loglog(h,
               abs((Mid_sol - f(2., 0.)) / f(2., 0.)),
               '-g',
               label="Midpoint method",
               linewidth=2.)
    plt.loglog(h,
               abs((RK4_sol - f(2., 0.)) / f(2., 0.)),
               '-k',
               label="Runge Kutta 4",
               linewidth=2.)
    plt.xlabel("$h$", fontsize=16)
    plt.ylabel("Relative Error", fontsize=16)
    # plt.title("loglog plot of relative error in approximation of $y(2)$.")
    plt.legend(loc='best')
    # plt.savefig('relative_error.pdf')
    plt.show()
    plt.clf()
Esempio n. 13
0
def Fig4():
	a, b, ya = 0., 8., 1.
	from math import exp, sin, cos
	def f(x):
		return exp(sin(x))
	
	def ode_f(x,y): 
		return np.array([y*cos(x)])
	
	# Number of subintervals
	N1 = np.array([10,20,40,80,160,320,640,1280,2560,5120,
	     			10240,20480,40960,81920,163840,327680,655360,1310720])
	N2, N3 = N1[:12],N1[:10]
	Euler_sol, Mid_sol, RK4_sol = np.zeros(len(N1)), np.zeros(len(N2)), np.zeros(len(N3))
	
	for j in range(len(N1)): 
		Euler_sol[j] = euler(ode_f,ya,a,b,N1[j])[-1]
	for j in range(len(N2)):	
		Mid_sol[j] = midpoint(ode_f,ya,a,b,N2[j])[-1]
	for j in range(len(N3)):
		RK4_sol[j] = RK4(ode_f,ya,a,b,N3[j])[-1]
	
	
	# Data for a Table?
	euler_error = np.concatenate((abs(( Euler_sol - f(b))/f(b) )[:,np.newaxis], N1[:,np.newaxis]),axis=1)
	rk4_error = np.concatenate((abs(( RK4_sol - f(b))/f(b) )[:,np.newaxis], 4*N3[:,np.newaxis]),axis=1)
	
	# Plot number of function evaluations versus relative error
	fig = plt.figure()
	plt.loglog(N1, abs(( Euler_sol - f(b))/f(b) ),'-b', label="Euler method"   , linewidth=2.)
	plt.loglog(2*N2, abs(( Mid_sol - f(b))/f(b) ),  '-g', label="Midpoint method", linewidth=2. )
	plt.loglog(4*N3, abs(( RK4_sol - f(b))/f(b) ),  '-k', label="Runge Kutta 4"  , linewidth=2. )
	ax = fig.add_subplot(111)
	plt.ylabel("Error", fontsize=16)
	plt.xlabel("Functional Evaluations", fontsize = 16)
	ax.legend(loc='best')
	# ax.invert_xaxis()
	# plt.savefig('Fig4.pdf')
	plt.show()
	plt.clf()