import numpy as np import integrate_utils as IU #================================================================ # Functions #================================================================ def ft(t): return 3*t**2*np.exp(t**3) def int_ft(t): return np.exp(t**3) #================================================================ # Calcs #================================================================ exact_sol = int_ft(1) - int_ft(0) trap = IU.trapezoidal(ft, 0, 1, 1000) mid = IU.midpoint(ft, 0, 1, 1000) #================================================================ # Results #================================================================ print 'Exact solution:', exact_sol print 'Trapezoidal method:', trap print ' difference', exact_sol-trap print 'Midpoint method:', mid print ' difference', exact_sol-mid
def g(y): return 2 * y * np.exp(y**2) #================================================ # compute mean value #================================================ x = np.linspace(0, np.pi + (np.pi / 1000), 1000) y = np.linspace(0, 1 + 1 / 1000, 1000) print np.sum(x) / 1000, np.sum(y) / 1000 #================================================ # compute integral #================================================ #using trapezoidal method f_int = int_utils.trapezoidal(f, 0, np.pi, 1000) g_int = int_utils.trapezoidal(g, 0, 1, 1000) print f_int, g_int #================================================ # plotting #================================================ plt.figure(1) ax = plt.subplot(111) ax.plot(x, f(x), 'r-', lw=1, label='f(x)') ax.plot(y, g(y), 'b-', lw=1, label='g(y)') #mean values are notably lower than values obtained through numerical integration
return np.exp(t**3) #===================== # imports #===================== import numpy as np import integrate_utils as iu #===================== #computations #===================== # integrate fct_t using trapezoid, midpoint methods trap_val = iu.trapezoidal(fct_t, 0, 1, 100) mid_val = iu.midpoint(fct_t, 0, 1, 100) # the exact integral solution exact_val = integral_fct_t(1) - integral_fct_t(0) #===================== #print results #===================== print('The integration of f(t) using the trapezoidal method is: ' + str(trap_val)) print('The integration of f(t) using the midpoint method is: ' + str(mid_val)) print('The exact integration of f(t) is: ' + str(exact_val))
1. Compute the integral of the following function within the given domain. Use both midpoint and trapezoidal methods! Compare your results to the exact solution of the definite integral a.) f(t) = 3t**2*e**t**3 """ import numpy as np import integrate_utils as iu def ft(t): return 3 * (t**2) * np.exp(t**3) def integration_ft(t): return np.exp(t**3) sol = integration_ft(1) - integration_ft(0) trapazoidal = iu.trapezoidal(ft, 0, 1, 100) midpoint = iu.midpoint(ft, 0, 1, 100) print 'solution: ', sol print 'Trapezoidal method: ', trapazoidal print 'Difference', sol - trapazoidal print 'Midpoint method: ', midpoint print 'Difference ', (sol - midpoint)
return 3*(t**2) * (e**(t**3)) a = f_t(1) print(a) def int_f_t(t): return (e**(t**3)) b = int_f_t(0) print(b) #============================exact solution==================================== ex_sol = int_f_t(1) - int_f_t(0) #===================Apply trapezoidal and midpoint methods ==================== trap_result = int_u.trapezoidal(f_t, 0, 1, 10) midpoint_result = int_u.midpoint(f_t, 0, 1, 10) #==results(when using %10.2f, 10 is number of spaces, 2 is nuber of decimals)== print("Trapezoidal rule results: %.20f" %trap_result) print("Midpoint method results: %.20f" %midpoint_result) """ Trapezoidal rule results: 1.75204264178808499786 Midpoint method results: 1.70148276900918782317 """
#============================================================================== def f(x): return np.sin(x) def g(x): return 2 * x * np.exp(x**2) def meanvalue(fct, x0, xn): """ Computes the mean value of a function by averaging 1000 sampled values of the function Input: fct - function to find mean value of x0 - left bound xn - right bound """ xvals = np.linspace(x0, xn, 1000) return fct(xvals).sum() / len(xvals) #============================================================================== #computations #============================================================================== fintegral = integrate_utils.trapezoidal(f, 0, np.pi, 1000) print('Function f(x), integral is', fintegral, 'mean value is', meanvalue(f, 0, np.pi)) gintegral = integrate_utils.trapezoidal(g, 0, 1, 1000) print('Function g(x), integral is', gintegral, 'mean value is', meanvalue(g, 0, 1))
# =========================2============================= # Parameters # ======================================================= xmin = 0 xmax = 1 N = 10 # =========================3============================= # Numerical Integration # ======================================================= # exact solution f_IntExact = fct_F(xmax) - fct_F(xmin) # numerical approx f_IntTrap = int_utils.trapezoidal(fct_f, xmin, xmax, N) f_IntMid = int_utils.midpoint(fct_f, xmin, xmax, N) # compare exact and numerical print('Exact Integral:', f_IntExact) print('Numerical Approximation (Trapezoidal):', f_IntTrap) print('Numerical Approximation (Midpoint):', f_IntMid, '\n') for curr_n in range(10, 1000, 200): f_IntTrap = int_utils.trapezoidal(fct_f, xmin, xmax, curr_n) f_IntMid = int_utils.midpoint(fct_f, xmin, xmax, curr_n) print('Increment dx:', float(xmax - xmin) / curr_n) print('Exact Integral:', f_IntExact) print('Numerical Approximation (Trapezoidal):', f_IntTrap) print('Numerical Approximation (Midpoint):', f_IntMid, '\n')
def f_t (t): return (3*t**2)*np.exp(t**3) def if_t(t): return np.exp(t**3) #========= Trapezoidal and Midpoint Evaluation ================================ x0 = 0 xn = 1 time_intervals = np.arange(0, 1, 100) trapf_t = integrate.trapezoidal( f_t, x0, xn, 100) #trapezoidal method midf_t = integrate.midpoint( f_t, x0, xn, 100) #midpoint method #real value of definite integral realValue = if_t(xn) - if_t(x0) print ('Integral using trapezoidal method: ', trapf_t) print ('Integral using midpoint method: ', midf_t) print ('Exact value of integral: ', realValue) #=============== Error calc for both methods ========== def errorCalc(real, approxValue): return (np.absolute(approxValue - real)/real)*100 trapError = np.round_(errorCalc(realValue, trapf_t), 2)
r3 = np.linspace(0, 2, N) theta3 = np.linspace(0, np.pi, N) sol_exact3a = F3(r3[N - 1], theta3[N - 1]) - F3(r3[0], theta3[0]) x3 = np.linspace(0, 2, N) y3 = np.linspace(0, 1.5, N) sol_exact3b = W3(x3[N - 1], y3[N - 1]) - W3(x3[0], y3[0]) # ============================================================================= # Integration # ============================================================================= # For part 1. num_sol_1_midpoint = int_utils.midpoint(f1, t1[0], t1[N - 1], N) num_sol_1_trapezoid = int_utils.trapezoidal(f1, t1[0], t1[N - 1], N) # For part 2. # For part 3. num_sol3a = int_utils.monteCarlo(w3, g3, -2, 2, -2, 2, N2) num_sol3b = int_utils.monteCarlo(f3, g3, -1, 3, -1, 2.5, N2) # ============================================================================= # Comparisons # ============================================================================= # For part 1. print(
xmin = 0. xmax_f = np.pi xmax_g = 1 x_f = np.linspace(xmin, xmax_f, N) x_g = np.linspace(xmin, xmax_g, N) def f(x_f): return sin(x_f) def g(x_g): return 2 * (x_g) * (e**((x_g)**2)) ia_fx = inte.trapezoidal(f, xmin, xmax_f, N) ia_gx = inte.trapezoidal(g, 0, 1, 1000) iact_fx = -cos(x_f) iact_gx = (e**(x_g)**2) print ia_fx print iact_fx[999] print ia_gx print iact_gx[999] plt.figure(1) ax1 = plt.subplot(211) plt.plot(x_f, iact_fx, 'b') plt.plot(x_f, f(x_f), 'r') ax2 = plt.subplot(212) plt.plot(x_g, iact_gx, 'k') plt.plot(x_g, g(x_g), 'g')
# -*- coding: utf-8 -*- #python 2.7 """ Extra Credit Problem 1 Compute the integral of 3t^2e^(t^3) from 0 to 1 analytically and then using midpoint and trapezoidal method """ import numpy as np import integrate_utils #============================================================================== #function definitions #============================================================================== def fct(t): return 3 * t**2 * np.exp(t**3) def antideriv(t): return np.exp(t**3) #============================================================================== #computations #============================================================================== #using midpoint method print('The solution, using midpoint method, is ' + str(integrate_utils.midpoint(fct, 0, 1, 1000))) #using trapezoid method print('The solution, using trapzeoid method, is ' + str(integrate_utils.trapezoidal(fct, 0, 1, 1000))) #exact solution print('The exact solution is ' + str(antideriv(1) - antideriv(0)))
import numpy as np import matplotlib.pyplot as plt import integrate_utils as utils def fct_t(t): return 3 * t**2 * (np.e)**t**3 t_trap = utils.trapezoidal(fct_t, 0, 1, 1000) t_mid = utils.midpoint(fct_t, 0, 1, 1000) print('Trapezoidal: ', t_trap) print('Midpoint: ', t_mid) #def trapezoidal( fct_t, t0, tn, N): # """ # Composite Trapezoidal Method, eq. 3.17 page 60 in Linge & Langtangen # :param fct_x: - function whose integral is in question # :param x1: - integration bounds # :param x2: - integration bounds # :param N: - number of trapezoids, chose high number for high accuracy # :return: - integral of fct_x between x0 and xn # """ # t0 = 0 # tn = 1 # N = 1000 # dt = float(tn-t0)/N # # compute intergral: eq. 3.17 page 60 in Linge & Langtangen
def a_fct(x): return np.sin(x) def b_fct(x): return 2 * x * np.exp(x**2) #====== # computations #====== # numerical integrations of the part a and part b functions integral_a = iu.trapezoidal(a_fct, 0, np.pi, 1000) integral_b = iu.trapezoidal(b_fct, 0, 1, 1000) # estimated means for these functions mean_a = get_mean(a_fct, 0, np.pi) mean_b = get_mean(b_fct, 0, 1) #====== # print results #====== print('Part a.)') print('The calculated mean of f(x) using 1000 points is: ' + str(mean_a)) print('And the numerical integral is: ' + str(integral_a)) print('Part b.)') print('The calculated mean of g(x) using 1000 points is: ' + str(mean_b))
YPP = (fct_2[i - 1] - 2 * fct_2[i] + fct_2[i + 1]) / h**2 YP = (fct_2[i + 1] - fct_2[i - 1]) / (2 * h) res[i] = YPP - Ypp_2(x, fct_2[i], YP) res[-1] = fct_2[-1] - B return res # we need an initial guess iniT = (B - alpha) / (x3 - x4) * X2 Y_2 = fsolve(residuals, iniT) print(Y_2) ############################# Mean Value ################################ dataset_1 = Y x = np.mean(dataset_1) print('Mean Value 1 ', x) dataset_2 = Y_2 x_2 = np.mean(dataset_2) print('Mean Value 2 ', x_2) for n in np.arange(100, 1200, 200): fInt = int_utils.trapezoidal(fct_1, x1 - 1, x2 + 1, n) print('no. of random points', n, "num integral", round(fInt, 4), 'exact', round(2. / 3, 2)) for n in np.arange(100, 1200, 200): fInt = int_utils.trapezoidal(fct_2, x3 - 1, x4 + 1, n) print('no. of random points', n, "num integral", round(fInt, 4), 'exact', round(2. / 3, 2))
@author: Brady Lobmeyer Extra Credit assignment #1 """ import numpy as np import matplotlib.pyplot as plt import integrate_utils as inte e= np.e sin = np.sin cos = np.cos def f(t): return 3*(t**2)*(e**(t**3)) t= inte.trapezoidal(f, 0, 1, 100) print t x= inte.midpoint(f, 0, 1, 100) print x print (e**(1**3))-(e**(0**3)) #===================== # #2 #======================= N= 1000 xmin = 0 xmax_f= np.pi xmax_g= 1 x_f= np.linspace(xmin, xmax_f, N) x_g= np.linspace(xmin, xmax_g, N)
import integrate_utils as int_utils #============================================================================== # fct definition #============================================================================== def fct_t(t): # function defined return 3 * t**2 * np.exp(t**3) def int_f(t): # integrated function return np.exp(t**3) #============================================================================== # paramters #============================================================================== tmin, tmax = 0, 1 # initlal time value and final time value respectively N = 100 # can increase this value for increased accuracy #============================================================================== # compute integral #============================================================================== f_trapint = int_utils.trapezoidal(fct_t, tmin, tmax, N) # integrals f_midint = int_utils.midpoint(fct_t, tmin, tmax, N) f_exact = int_f(tmax) - int_f(tmin) # exact solution print('Trapezoidal Integral: ', f_trapint) print('Midpoint Integral: ', f_midint) print('Exact solution: ', f_exact)
#================================================================ # Parameters #================================================================ a_min = 0 a_max = np.pi b_min = 0 b_max = 1 a_x = np.linspace(a_min, a_max, 1000) b_x = np.linspace(b_min, b_max, 1000) #================================================================ # Calcs #================================================================ a_mean = np.mean(fx(a_x)) b_mean = np.mean(gx(b_x)) a_int = IU.trapezoidal(fx, a_min, a_max, 1000) b_int = IU.trapezoidal(gx, b_min, b_max, 1000) #================================================================ # Results #================================================================ print 'a)' print 'Mean value:', a_mean print 'Integral value:', a_int print 'Difference:', a_int - a_mean print 'b)' print 'Mean value:', b_mean print 'Integral value:', b_int print 'Difference:', b_int - b_mean
#============================================================================== # parameters #============================================================================== xminf, xmaxf = 0, np.pi # initial and final x values for f_x xming, xmaxg = 0, 1 # initial and final x values for g_x N = 1000 # function values for each x for both functions a_fx = np.linspace(xminf, xmaxf, N) a_gx = np.linspace(xming, xmaxg, N) #============================================================================== # compute integrals #============================================================================== # integrations using trapezoial method f_int = int_utils.trapezoidal(f_x, xminf, xmaxf, N) g_int = int_utils.trapezoidal(g_x, xming, xmaxg, N) #============================================================================== # compute means #============================================================================== # averages/means calculated f_mean = np.mean(f_x(a_fx)) g_mean = np.mean(g_x(a_gx)) print('mean value of f: ', f_mean, 'integral value of f: ', f_int) print('mean value of g: ', g_mean, 'integral value of g: ', g_int) # note that the mean of f is 2/pi since the x domain was over pi while the integral was 2.