def gauss_weights(N, a, b): """Return the sample points, sample weights for guassian intergration, code taken from example 5.2 in Newman""" x, w = gaussxw(N) xp = 0.5 * (b - a) * x + 0.5 * (b + a) wp = 0.5 * (b - a) * w return xp, wp
def gaussian(a, b): x, w = gaussxw(N) xp = 0.5 * (b - a) * x + 0.5 * (b + a) wp = 0.5 * (b - a) * w s = 0 for k in range(N): s += wp[k] * f(xp[k]) return s
def integrate(f,a,b,N): x,w = gaussxw(N) xp = 0.5*(b-a)*x +0.5*(b+a) wp = 0.5*(b-a)*w s=0 for k in range (N): s+= wp[k]*f(xp[k])/(xp[k]+1) return s
def GaussLeGde(func, a, b, N): x, w = gaussxw.gaussxw(N) x = 0.5*((b-a)*x + (b+a)) w = 0.5*w*(b-a) integral = 0.0 for i in range(N): integral += w[i]*func(x[i]) return integral
def gauss(f, a=0, b=1, N=25): x, w = gaussxw(N) # 采样点与权重 xp = 0.5 * (b-a) * x + 0.5 * (b+a) wp = 0.5 * (b-a) * w S = 0. for k in range(N): S += wp[k] * f(xp[k]) return S
def T(a, b, N, f, k, x0, m): #function that can take different a,b,N to calculate for T x, w = gaussxw(N) xp = 0.5 * (b - a) * x + 0.5 * (b + a) wp = 0.5 * (b - a) * w results = [] for i in range(N): results.append(4 * wp[i] * f(xp[i], x0, k, m)) return results, f(xp, x0, k, m), xp
def gauss(N, a, b, f, n): # Calculate the sample points and weights, then map them # to the required integration domain x,w = gaussxw(N) xp = 0.5*(b-a)*x + 0.5*(b+a) wp = 0.5*(b-a)*w # Perform the integration s = 0.0 for k in range(N): s += wp[k]*f(n,xp[k]) return s
def gaussion(f,a,b,N): # Calculate the sample points and weights, then map them # to the required integration domain x,w = gaussxw(N) # rescale weight and x values xp = 0.5*(b-a)*x + 0.5*(b+a) wp = 0.5*(b-a)*w s = 0.0 for k in range(N): s += wp[k]*f(xp[k]) return s
def DoubleInt(func, a, b, N): '''first argument must be a function that relies on at least 2 different variables''' x, w = gaussxw.gaussxw(N) x = 0.5*((b-a)*x + (b+a)) w = 0.5*w*(b-a) y = x integral = 0 for i in range(N): for j in range(N): integral += w[i]*w[j]*func(x[i],y[j], z = 0) return integral
def double_int(f, x1, x2, y1, y2, N): x, wx = gaussxw(N) # x and y have the same sample points and weights # rescale weight and x values xp = 0.5 * (x2 - x1) * x + 0.5 * (x2 + x1) wxp = 0.5 * (x2 - x1) * wx s = 0 for j in range(N): for i in range(N): s += wxp[j] * wxp[i] * f(xp[i], xp[j]) return s
def gauss_integral(x): from gaussxw import gaussxw from numpy import exp N = 100 a = 0.0 b = x t, w = gaussxw(N) tp = 0.5 * (b - a) * t + 0.5 * (b + a) wp = 0.5 * (b - a) * w s = 0.0 for k in range(N): s += wp[k] * (exp(tp[k]**2)) return '%.2f' % s
def gaussq(N, a, b): #Calculation of points and weights x, w = gaussxw(N) xp = 0.5 * (b - a) * x + 0.5 * (b + a) wp = 0.5 * (b - a) * w #Integration s = 0.0 for k in range(N): s += wp[k] * f(xp[k]) return (1 / (1 + z)) * s
def period(amplitude): a = 0 b = amplitude N = 20 x, w = gaussxw(N) xp = 0.5 * (b - a) * x + 0.5 * (b + a) wp = 0.5 * (b - a) * w integral = 0.0 for k in range(N): integral += wp[k] * f(xp[k], amplitude) return sqrt(8) * integral
def integral(n): x, w = gaussxw(100) a = 0 b = 1 xp = 0.5 * (b - a) * x + 0.5 * (b + a) wp = 0.5 * (b - a) * w i = 0 sum = i while i < 100: sum = sum + wp[i] * func(n, xp[i]) i = i + 1 return 2 * sum
def TrigIntegral(u_func, x_value, z_value, wavelength_value, sample_points, trig): # Define boundaries of the integral t_initial = 0.0 t_final = u_func(x_value, z_value, wavelength_value) # Calculate the sample points and weights, then map them # to the required integration domain t, w = gaussxw(sample_points) wp = 0.5*(t_final-t_initial)*w tp = 0.5*(t_final-t_initial)*t +0.5*(t_final+t_initial) # Do the integration integral = 0.0 for k in range(sample_points): integral += wp[k] * Integrand(tp[k], trig) return integral
def TrigIntegral(u_func, x_value, z_value, wavelength_value, sample_points, trig): # Define boundaries of the integral t_initial = 0.0 t_final = u_func(x_value, z_value, wavelength_value) # Calculate the sample points and weights, then map them # to the required integration domain t, w = gaussxw(sample_points) wp = 0.5 * (t_final - t_initial) * w tp = 0.5 * (t_final - t_initial) * t + 0.5 * (t_final + t_initial) # Do the integration integral = 0.0 for k in range(sample_points): integral += wp[k] * Integrand(tp[k], trig) return integral
def Force(z, a, b, N): '''first argument can be an array or single value that relies on at least 2 different variables''' def func(x,y,z): return (x**2 + y**2 + z**2)**(-3/2) x, w = gaussxw(N) xp = 0.5*((b-a)*x + (b+a)) wp = 0.5*w*(b-a) y = xp integral = 0 for i in range(N): for j in range(N): integral += wp[i]*wp[j]*func(xp[i],y[j], z) return integral
def S(u_func, x_i, sample_points): # Define integrand of S(u) def g(t): return sin(0.5 * pi * t**2) # Define boundaries of the integral, and number of sample points N t_initial = 0.0 t_final = u_func(x_i,z,wavelength) # Calculate the sample points and weights, then map them # to the required integration domain t, w = gaussxw(sample_points) tp = 0.5*(t_final-t_initial)*t +0.5*(t_final+t_initial) wp = 0.5*(t_final-t_initial)*w # Do the integration integral_S = 0.0 for k in range(sample_points): integral_S += wp[k]*g(tp[k]) return integral_S
def S(u_func, x_value, z_value, wavelength_value, sample_points): # Define integrand of S(u) def g(t): return sin(0.5 * pi * t**2) # Define boundaries of the integral, and number of sample points N t_initial = 0.0 t_final = u_func(x_value, z_value, wavelength_value) # Calculate the sample points and weights, then map them # to the required integration domain t, w = gaussxw(sample_points) tp = 0.5*(t_final-t_initial)*t +0.5*(t_final+t_initial) wp = 0.5*(t_final-t_initial)*w # Do the integration integral_S = 0.0 for k in range(sample_points): integral_S += wp[k]*g(tp[k]) return integral_S
def integrale_gausienne(fonction, a, b, N): """ Fonction qui calcule l'intégrale de la fonction entre les bornes a et b de façon numérique en utilisant la méthode gauss avec N pas. :param fonction: La fonction à intégrer. :param a: La borne inférieur. :param b: La borne supérieur. :param N: Nombre de pas. :return: La valeur de l'intégrale. """ x, w = gaussxw(N) xp = 0.5 * (b - a) * x + 0.5 * (b + a) wp = 0.5 * (b - a) * w # Perform the integration s = 0.0 for k in range(N): s += wp[k] * fonction(xp[k]) return s
def cv(T): x, w = gaussxw(50) V = 1 rho = 6.022 * 10e28 theta_D = 428 a = 0 b = theta_D / T xp = 0.5 * (b - a) * x + 0.5 * (b + a) wp = 0.5 * (b - a) * w sum = 0 i = 0 while i < 50: sum = sum + wp[i] * integrand(xp[i]) i = i + 1 Kb = 1.38065 * 10e-23 sum = sum * 9 * rho * V * Kb * (T / theta_D)**3 return sum
def C(u_func, x_i): # Define integrand of C(u) def f(t): return cos(0.5 * pi * t**2) # Define boundaries of the integral, and number of sample points N t_initial = 0.0 t_final = u_func(x_i, z, wavelength) # Calculate the sample points and weights, then map them # to the required integration domain t, w = gaussxw(N) tp = 0.5 * (t_final - t_initial) * t + 0.5 * (t_final + t_initial) wp = 0.5 * (t_final - t_initial) * w # Do the integration integral_C = 0.0 for k in range(N): integral_C += wp[k] * f(tp[k]) return integral_C
def gaussian_quadrature(func, a, b, N): """Calculate integral of some function from a to b with N sample points args: - func: function to be integrated - a: lower limit of integration - b: upper limit of integration - N: number of sample points """ x, w = gaussxw(N) xp = 0.5 * (b - a) * x + 0.5 * (b + a) wp = 0.5 * (b - a) * w integral = 0. for k in range(N): integral += wp[k] * func(xp[k]) return integral
def gaussian_quadrature(func, z, a, b, N): """Calculate integral of some function from a to b with N sample points args: - func: function to be integrated - z: a constant to be passed to function - a: lower limit of integration - b: upper limit of integration - N: number of sample points """ x, w = gaussxw(N) xp = 0.5*(b - a)*x + 0.5*(b + a) wp = 0.5*(b - a)*w integral = 0. for i in range(N): for j in range(N): integral += wp[i]*wp[j]*func(xp[i], xp[j], z) return integral * 6.674*1.e-11 * 100 * z
def D_gauss(x: float, N: int): """Numerically computes Dawson's function using Gauss' method. INPUT: x as per question notation. N is the number of slices. OUTPUT: Dawson's Function for N slices and x """ #From lecture notes and pg 170 Newman # call gausswx for xi, wi xi, w = gaussxw(N) # map them to the required integration domain xi = 0.5 * (x) * xi + 0.5 * (x) w = 0.5 * (x) * w # initialize integral to 0. I = 0. # loop over sample points to compute integral for k in range(N): I += w[k] * D_f(xi[k]) return I * np.exp(-x**2)
def efficiency(T): N = 100 planck = 6.62607004e-34 # Joules * s boltz = 1.38064852e-23 # Joules / K c = 299792458 # m / s lambda1 = 3.9e-7 # metres lambda2 = 7.5e-7 # metres x0 = planck*c/(lambda2*boltz*T) xf = planck*c/(lambda1*boltz*T) def I(x): return (x**3)/(np.exp(x) - 1) # overflow? x,w = gaussxw(N) xp = 0.5*(xf-x0)*x + 0.5*(xf+x0) wp = 0.5*(xf-x0)*w s = 0.0 for k in range(N): s += wp[k]*I(xp[k]) return 15/(np.pi**4)*s
def gauss(a: float, b: float, N: int, f): """Numerically computes the integral using the gauss method of an input function func of a single variable, from a to b with N slices. Input: a, lower integration bound, b upper, N number of slices, f function under integral Output: Gauss integral of f from a to b using N slices.""" # Based on lecture notes and page 170 of newman # call gausswx for xi, wi x, w = gaussxw(N) # map them to the required integration domain xp = 0.5 * (b - a) * x + 0.5 * (b + a) wp = 0.5 * (b - a) * w # initialize integral to 0. I = 0. # loop over sample points to compute integral for k in range(N): I += wp[k] * f(xp[k]) return I
legend() show() x = linspace(-10, 10, 200) plot(x, ksi(30, x)) show() #Integration uncertainty = lambda n, x: x**2 * ksi(n, x)**2 sys.path.append('cpresources') from gaussxw import gaussxw N = 100 x, w = gaussxw(N) # 5.68 def x_sq(n): a = -1 b = 1 xp = 0.5 * (b - a) * x + 0.5 * (b + a) wp = 0.5 * (b - a) * w y = (1 + xp**2) / (1 - xp**2)**2 * uncertainty(n, xp / (1 - xp**2)) s = sum(y * wp) return s n = 5
sys.path.append('C:\Users\CHRIS\Documents\Python Scripts\LearningScripts\ComputationalPhysicsExercises\cpresources') import gaussxw as G def f(x): return np.exp(x)*(x**4)/(np.exp(x) - 1)**2 def cv(T,x,w): xp = 0.5*T*x + 0.5*T wp = 0.5*T*w #calculate integral CV = sum(f(xp)*wp) return CV N = 50 x,w = G.gaussxw(N) #define constants V = 1E-3 rho = 6.022E28 theta = 428 Boltz = 1.38E-23 T = np.linspace(5,500,100) kappa = 9*V*rho*Boltz*(T/theta)**3 Heat_Cap = np.array([cv(theta/Tn,x,w) for Tn in T])*kappa plot(T,Heat_Cap) show()
from gaussxw import gaussxw def f(x): return x**4 - 2*x + 1 N=3 a=0. b=2.0 # Calculate the sample points and weights xp = gaussxw(N) # Map sample points and weights to integration limits xp = 0.5*(b-a)*x + 0.5*(b+a) wp = 0.5*(b-a)*w # Perform integration s=0. for k in range(N): s += wp[k]*f(xp[k]) print s
import numpy as np import integration as ig import gaussxw as gauss import matplotlib.pylab as plt def F_1(x): return np.reciprocal(np.sqrt(np.math.sin(x))) No_Sample_list=[10,50,100,1000,5000] res_F_1=[] for N in No_Sample_list: gauss_x,gauss_w=gauss.gaussxw(N) gauss_x_N,gauss_w_N=ig.gauss_quad(gauss_x,gauss_w,0,1) sum=0 for i in range(N): sum+=F_1(gauss_x_N[i])*gauss_w_N[i] res_F_1.append(sum) for i in range(len(res_F_1)): print("When the number of sample is ",No_Sample_list[i],', the result is',res_F_1[i]) F_1_trap=ig.numerical_method(ig.trapezoidal,None,F_1,lambda x,y:(x-y)/3.0,0.0001,1,10,10e-7) for x in [0.2,0.1,0.01,0.001,0.00000001]: F_1_trap.adaptive_cal(x,1,10e-7,0) print("I(",x,")=",F_1_trap.res[-1]) ''' x_coord,y_coord=F_1_trap.adaptive_cal(0.001,1,10e-7,1) y_coord=[y_coord[-1]-y for y in y_coord] x_coord=[np.math.log(x) for x in x_coord] plt.plot(x_coord,y_coord) plt.show() ''' def F_2(x):
tight_layout() savefig('Lab03-Q1a-Fig'+str(j+1)+'.png') #------------------------------------------------------------------------ # Relativistic period x0_range = linspace(1,10*xc,1000) def g(x): return c*sqrt(((0.5*k*(x0**2-x**2)*(2.0*m*c**2+0.5*k*(x0**2-x**2))) \ /(m*c**2+0.5*k*(x0**2-x**2))**2)) def integrand(x): return 4.0*g(x)**-1 T_relativistic = zeros(len(x0_range)) # x and w in interval -1 to 1 x,w = gaussxw(200) for i in range(len(x0_range)): s = 0.0 x0 = x0_range[i] xp = 0.5*x0*x + 0.5*x0 wp = 0.5*x0*w for j in range(200): s += wp[j]*integrand(xp[j]) T_relativistic[i] = s # Plots for Fourier Transformation, and the method used in lab3-Q2b figure() subplot(211) plot(abs(ft_1m)/max(abs(ft_1m)),label='pos_1m') plot(abs(ft_xc)/max(abs(ft_xc)),label='pos_xc')
import numpy as np from scipy.integrate import quad,fixed_quad import pdb ## --- define function to integrate --- def f(x): return x**6 - 2.*x + 1. ## define constants a = 0. #lower limit of integration b = 2. #upper limit of integration N = 6 #number of "slices" # get weights and positions x1,w1 = gaussxw(N) x1_new = 0.5 * (b - a) * x1 + 0.5 * (b + a) w1_new = 0.5 * (b - a) * w1 # compute integral s = 0 for k in range(N): s += w1_new[k] * f(x1_new[k]) print 's=',s ## new way ## # using scipy pre-defined function with given N I = fixed_quad(f,a,b,n=N) print 'integral fixed degree gauss', I[0]
while True: f1, f2, f3, f4 = feval(fn, [x1, x2, x3, x4], args) if x4 - x1 > tol: if f2 < f3: x4 = x3 x3 = x2 x2 = getx2(x1, x4) if f3 < f2: x1 = x2 x2 = x3 x3 = getx3(x1, x4) elif x4 - x1 < tol: break return x1 + (x4 - x1) / 2. # Import Gaussian weights and points for an interval from -1 to 1 xs, ws = gaussxw(Nsamp) # Specify target accuracy of 1 K eps = 1. # Decide bracketing region based on temperature plot from lab4_q6a T1 = 6000 T4 = 8000 # Call golden min to find the minimum of the negative effeciency Tf = golden_min([T1, T4], neta, eps, args=[xs, ws]) print 'Maximum effeciency occurs at T = ', Tf, 'K'
# From the first assignment k = 12.0 m = 1.0 c = 2.998e8 xc = 8.654e7 # N = 8 N = 16 # N = 200 a = 0.0 x0 = np.linspace(0.01, 1, N) x, w = gaussxw(N) xp = 0.5 * (x0 - a) * x + 0.5 * (x0 + a) wp = 0.5 * (x0 - a) * w T = [] for k in range(N): T.append(wp[k] * g(xp[k])) # For some reason, the integral is about 1e9 too small, I multiply to fix this period = map(lambda T: T * 4 * 5e8, T) # print period plt.plot(x0, period, label="Calc Periods") plt.axhline(y=2 * np.pi * np.sqrt(m / k), color="black")
# Here's how the package works: # In[81]: from gaussxw import gaussxw def f(x): return x**4 - 2 * x + 1 N = 3 # number of steps a = 0.0 # lower limit of integration b = 2.0 # upper limit of integration x, w = gaussxw(N) # gaussxw(N) returns the sample points x and weights w # for the reference integral (-1,1) # Now define x' and w' to be the sample points and weights # for the interval (a,b). We derived this transformation # in lecture 5. xp = 0.5 * (b - a) * x + 0.5 * (b + a) wp = 0.5 * (b - a) * w # Now estimate the integral of f by summing # the sample points and the weights total = 0.0 for k in range(N): total += wp[k] * f(xp[k])
import numpy as np from scipy.integrate import quad, fixed_quad ## --- define function to integrate --- def f(x): return x**4 - 2. * x + 1. ## define constants a = 0. #lower limit of integration b = 2. #upper limit of integration N = 3 #number of "slices" # get weights and positions x1, w1 = gaussxw(N) x1_new = 0.5 * (b - a) * x1 + 0.5 * (b + a) w1_new = 0.5 * (b - a) * w1 # compute integral s = 0 for k in range(N): s += w1_new[k] * f(x1_new[k]) print 's=', s ## new way ## # using scipy pre-defined function with given N I = fixed_quad(f, a, b, n=N) print 'integral fixed degree gauss', I[0]
z2 = 1 * e_ch k = alp * z1 * z2 # V=k*z1*z2*u E = 1e3 * e_ch # 1 keV # Define a and b n = 3 til_w = ones(n, float) til_x = ones(n, float) # Define w and x x, w = gaussxw(n) # Define til_w and til_x # Integration for q in arange(2.5e-15, 1e-10, 2.5e-15): s = q psi = 0 l = (2 * m * E * s * s) ** 0.5 a = 0 b = (1 / (2 * E * s * s)) * (-k + (k * k + 4 * E * E * s * s) ** 0.5) for i in range(n): til_w[i] = w[i] * (b - a) * 0.5 til_x[i] = ((b - a) * x[i] + (b + a)) * 0.5
xs,ws = args a = h*c/(wv2*kB*T) # lower limit b = h*c/(wv1*kB*T) # upper limit x = 0.5*(b-a)*xs + 0.5*(b+a) # scale points w = 0.5*(b-a)*ws # scale weights eta = 0 # start integration sum for n in range(Nsamp): eta += w[n]*etaint(x[n]) eta *= (15./np.pi**4) return eta # Choose number of sample points for Gaussian quadrature Nsamp = 100 # Import Gaussian weights and points for an interval from -1 to 1 xs,ws = gaussxw(Nsamp) # Create temperature array T = np.arange(300,10000) # K # Create empty array to hold resulting etas etas = [] # Calculate eta for each T value for i in range(len(T)): print 'Temperature rising ...',T[i],'K' etacal = eta(T[i],(xs,ws)) etas.append(etacal) # Plot eta vs T plt.title('Efficiency of an incandescent bulb')