コード例 #1
0
def rms_p(n):
    """ INPUT: nth energy level
    
    OUTPUT: value of the root-mean-square momentum(p) """
    def rms_pintegrand(z):
        def x(z):
            return z / (1 - z)

        if n == 0:
            return (np.abs(
                (1 / np.sqrt(2**n * math.factorial(n) * np.sqrt(np.pi))) *
                np.e**(-x(z)**2 / 2) *
                (-x(z) * h(0, x(z)) + 2 * n * h(0, x(z))))
                    )**2  #integrand of <p> for n=0
        elif n == 1:
            return (np.abs(
                (1 / np.sqrt(2**n * math.factorial(n) * np.sqrt(np.pi))) *
                np.e**(-x(z)**2 / 2) *
                (-x(z) * h(1, x(z)) + 2 * n * h(1, x(z))))
                    )**2  #integrand of <p> for n=1
        else:
            return (np.abs(
                (1 / np.sqrt(2**n * math.factorial(n) * np.sqrt(np.pi))) *
                np.e**(-x(z)**2 / 2) * (-x(z) * h(n, x(z)) + 2 * n * h(
                    (n - 1), x(z)))))**2  #integrand of <p> for n>2

    #integral of uncertainty of momentum
    I = 0.0
    N = 100
    a = 0
    b = 1
    x, w = gaussxwab(N, a, b)
    for k in range(N):
        I += w[k] * rms_pintegrand(x[k])
    return np.sqrt(2 * I)
コード例 #2
0
ファイル: Lab03_Q1b.py プロジェクト: bmcq55/schoolprojects
def prob_blowing_snow(u10, Ta, th, N):
    """
    Function that uses gaussian quadrature to calculate 
    the probability of blowing snow

    Parameters
    ----------
    u10 : float
        Average hourly windspeed at 10m.
    Ta : float
        Average hourly temperature
    th : float
        Snow surface age.
    N : int
        Number of sample points.

    Returns
    -------
    float
        Probability of blowing snow in these conditions.

    """
    # Mean and standard deviation wind speed
    ubar = 11.2 + 0.365*Ta + 0.00706*Ta**2 + 0.9*np.log(th)
    delta = 4.3 + 0.145*Ta + 0.00196*Ta**2
    
    # Integrand as a function u, wind speed
    integrand = lambda u : np.exp(-(ubar-u)**2/(2*delta**2))
    
    # Calculation of integral using gaussian quadrature
    s, w = gaussxwab(N, 0, u10)
    integral = np.sum(w*integrand(s))
    
    # Normalize integral to calculate probability
    return integral/(np.sqrt(2*np.pi)*delta)
コード例 #3
0
def quad(a, b, f, n):
    x, w = gaussxwab(n, a, b)
    integral = []
    for i in range(n):
        integral.append(w[i] * f(x[i]))
    resultado = sum(integral)
    return resultado
コード例 #4
0
def int_gauss(f, a, b, N, error=0.0):
    k = np.arange(N)
    s, w = gaussxwab(N, a, b)
    result = f(s[k])
    while w.ndim != result.ndim:
        w = w[:, None]
    return np.nansum((w * result), axis=0)
コード例 #5
0
def gaussian_quadrature(f, a, b, n):
    """
    Integrate the function f from a to b using gaussian quadrature
    with n slices.
    
    Code is based on example on p.170 in the textbook.

    Parameters
    ----------
    f : (float -> float)
        1-D continuous function.
    a : float
        Lower limit of integration.
    b : float
        Upper limit of integration.
    n : int
        Number of slices.

    Returns
    -------
    Approximate value of f integrated from a to b.

    """
    x, w = gaussxwab(n, a, b)
    return np.sum([w[i] * f(x[i]) for i in range(n)])
コード例 #6
0
def gauss_quad(func, x_min, x_max, N=1000, **kwargs):
    """
    Gaussian quadrature method to integrate a function between two given limits.

    Parameters
    ------------
    func : function
        Function to be integrated.
    x_min : scalar
        Lower limit of integration.
    x_max : scalar
        Upper limit of integration.
    N : int,optional
        Number of points for quadrature method.
    **kwargs :
        Extra arguments for the integrand function func.

    Returns
    ---------
    value : scalar
        Integration value.

    """

    xp, wp = gaussxwab(N, x_min, x_max)

    y = func(xp, **kwargs)
    int_value = sum(wp * y)

    return int_value
コード例 #7
0
def integrateG(f,n,a,b,N):
	x,w = gaussxwab(N,a,b)
	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],n)
	return s
def cv(Temp):
    # do __sum__
    TEMP = Temp / debeye
    __sum__ = 0.0
    x,w = gaussxwab(50,0,1/TEMP)
    for k in range(50):
        __sum__ += w[k] * f(x[k])
    return __sum__ * cv_0 * (TEMP**3)
コード例 #9
0
def normalizeAndGraph(E):
    n = 100
    x,w = gaussxwab(n,-L/2,0)
    s = 0
    for i in range(n):
        ds = ((hbar**2)/2*m*(V(x[i]-E)))**2
        s += w[i]*ds
    phi = 0.5/sqrt(s)
    solve(E, phi, 1)
コード例 #10
0
def dawson_gauss(x, N):

    a = 0.0
    b = x
    s, w = gaussxwab(N + 1, a, b)

    coeff = np.exp(-x**2)
    integral = dawson_integral(s, w)
    return coeff * integral
コード例 #11
0
def gamma(func2, C):
    N = 200
    a = 0.0
    b = 1.0
    x, w = gaussxwab(N, a, b)
    s = 0.0
    for k in range(N):
        s += w[k] * func2(C, x[k])
    return s
コード例 #12
0
def expect_p2(n, p):
    #function to be integrated over
    def func(x):
        return ((1+x**2)/((1-x**2)**2))*(np.abs(wavefunc_derivative(n,(x/(1-x**2)))))**2
    N,a,b = p
    x,w = gaussxwab(N,a,b)
    I = 0.0
    for i in range(N):
        I += w[i]*func(x[i])
    return I
コード例 #13
0
ファイル: indep_q2b.py プロジェクト: NatalieP-J/PHY407
def gaussint(fn,Nsamp,lowlim,uplim,args = False):
	"""
	Returns the integral of fn from lowlim to uplim using Gaussian 
	quadrature with Nsamp sample points.
	"""
	x,w = gaussxwab(Nsamp,lowlim,uplim) # gets points and weights
	s = np.zeros(np.shape(args))
	for i in range(Nsamp):
		s += w[i]*fn(x[i],args) # evaluate fn at points and weight it
	return s
コード例 #14
0
ファイル: Lab4_Q2.py プロジェクト: fancent/PHY407
def Efficiency(l1, l2, T, N, f):
    """
    This function uses Gaussian Quadrature method to calculate the integrals
    needed for the efficiency given the bounds of wavelengths.
    """
    x, w = gaussxwab(N, l1, l2)
    results = 0
    for i in range(N):
        results += w[i] * f(x[i], T)
    return results
コード例 #15
0
ファイル: indep_q2c.py プロジェクト: NatalieP-J/PHY407
def gaussint(fn, Nsamp, lowlim, uplim, args=False):
    """
	Returns the integral of fn from lowlim to uplim using Gaussian 
	quadrature with Nsamp sample points.
	"""
    x, w = gaussxwab(Nsamp, lowlim, uplim)  # gets points and weights
    s = np.zeros(np.shape(args))
    for i in range(Nsamp):
        s += w[i] * fn(x[i], args)  # evaluate fn at points and weight it
    return s
コード例 #16
0
def dbasis_quad(curve, N, i, j, k, t, d):
    """
        For E norms:
        
        Multiply 2 Derivative Basis Functions and Integrate
        
        Modified to use correct starting and end vertices for these product basis
            functions.
        N   = order of accuracy of the integration - should match the order of the new D
                basis Dbasis function
        i   = the ith function in the Mij matrix
        j   = the jth function im the Mij matrix
        p   = degree (actually passing order) of the curve
        t   = knot vector
        d   = derivative order
    """
    p = curve.p

    ##  ESTABLISH THE LIMITS OF INTEGRATION:
    ##      a=min, b=max
    ij_min = max(i, j)  #could use this always assuming assending knot order...
    ij_max = min(k + i, k + j)

    #Now we need to divide the span into continuous segments, if not already continuous...
    rel_knot_set = list(set(
        t[ij_min:ij_max +
          1]))  # oh boy... am I intoducing something weird here?
    rel_knot_set = sorted(rel_knot_set)  #cruical!

    # Calculate the sample vertices and weights, then map them
    # to the required integration domain
    s = 0.0
    if (len(rel_knot_set) < 2):
        pass
    else:
        for ii in range(len(rel_knot_set) - 1):
            a = rel_knot_set[ii]
            b = rel_knot_set[ii + 1]
            x, w = gaussxwab(N, a, b)
            """
                returns integration points, x
                and
                integration weights, w
                mapped to the integral of a to b
            """

            # Perform the integration
            b1 = np.zeros((curve.n, curve.n), float)
            for pt in range(N):
                b1[:, :] = 0.0
                span = curve.FindSpan(x[pt])
                curve.DersBasisFunc(span, x[pt], b1[:, span - p:span + 1])
                s += w[pt] * b1[d, i] * b1[d, j]  #sum over all N

    return s
コード例 #17
0
def eta(T):
    def f(x):
        return x**3/(np.exp(x)-1)
	#Quadratura gaussiana com N = 100 usando a gaussiana do mark newman.
    N=100
    x,w=gaussxwab(N,Inferior/T,Superior/T)
    integral=0.0
    for k in range(N):
        integral+=w[k]*f(x[k])

    return 15/np.pi**4*integral
コード例 #18
0
ファイル: gaussint.py プロジェクト: NatalieP-J/PHY407
def gaussint(fn,Nsamp,lowlim,uplim):
	"""
	Returns the integral of fn from lowlim to uplim using Gaussian 
	quadrature with Nsamp sample points.

	"""
	x,w = gaussxwab(Nsamp,lowlim,uplim) # gets points and weights
	s = 0.0 # start sum at zero
	for i in range(Nsamp):
		s += w[i]*fn(x[i]) # evaluate fn at points and weight it
	return s
コード例 #19
0
def gauss_q_integral_calc(N, n, a, b, f):
    """
    N: number of sample points.
    a,b: interval lef and right boundary.
    f: the function we want its integral.
    *Inspired from the Textbook.
    """
    x, w = gaussxwab(N, a, b)
    s = 0.0
    for j in range(N):
        s += (w[j] * f(x[j], n))
    return s
コード例 #20
0
def quad(a, b, n):
    I2 = []
    resultado = []
    theta, w = gaussxwab(n, a, b)
    for m in range(3):
        for x in X:
            for i in range(n):
                I2.append(float(w[i] * f(theta[i], m, x)))
            resultado.append(float(sum(I2)))
            I2 = []
        RES2.append(resultado)
        resultado = []
def eta(T):
    def f(x):
        return x ** 3 / (exp(x) - 1)

    # We use Gaussian quadrature with N = 100 sample points
    N = 100
    x, w = gaussxwab(N, lower_constant / T, upper_constant / T)
    integral = 0.0
    for k in range(N):
        integral += w[k] * f(x[k])

    return 15 / pi ** 4 * integral
コード例 #22
0
def gaussian(f, a, b, n=n):
    # removes ambiguity error with gauss method
    f = g

    x, w = gaussxwab(n, a, b)

    # while(error > accuracy):
    #     n = n*2
    #     x, w = gaussxwab(n, a, b)
    #     print(n)
    #     print(error)
    return sum(f(x) * w)
コード例 #23
0
def finite_integration(f, frm=0.0, to=pi, method='simpson', N=60):
    """Calculates finite integration of a function (f) inside given interval
    by either Simpson method or Gaussian quadrature
    
    Positional arguments:
    f -- function to integrate (type function)
    
    Keyword arguments:
    frm -- lower bound of integration (default 0.0)
    to -- upper bound of integration (default pi)
    method -- method of numeric integration to run [options 'simpson',
    'gauss'] (default 'gauss')
    n -- number of samples to use (defualt 60)
    """

    # Simpson method case
    if method == 'simpson':
        terms = []  # to feed with simpsons formula sum terms
        delta_x = (to - frm) / N

        # 1st term caculation
        terms.append(delta_x * (f(frm) + f(to)) / 3)

        # 2nd term caculation
        s, k = 0.0, 1
        while k <= N - 1:
            s += f(frm + k * delta_x)
            k += 2
        terms.append(4 * delta_x * s / 3)

        # 3rd term caculation
        s, k = 0.0, 2
        while k <= N - 2:
            s += f(frm + k * delta_x)
            k += 2
        terms.append(2 * delta_x * s / 3)

        return sum(terms)

    # Gaussian quadrature case
    if method == 'gauss':
        from gaussxw import gaussxwab

        # Calculates os samples nd weights inside [frm, to] interval
        x, w = gaussxwab(N, frm, to)

        # Does summation
        s = 0.0
        for k in range(N):
            s += w[k] * f(x[k])

        return s
コード例 #24
0
def T(a):
    def f(x):
        def v(y):
            return y**4

        return 1 / sqrt(v(a) - v(x))

    x, w = gaussxwab(n_points, 0, a)
    integral = 0.0
    for k in range(n_points):
        integral += w[k] * f(x[k])

    return sqrt(8) * integral
コード例 #25
0
def T(a):
    def f(x):
        def v(y):
            return y**4

        return 1 / np.sqrt(v(a) - v(x))

    x, w = gaussxwab(N, 0, a)
    integral = 0.0
    for k in range(N):
        integral += w[k] * f(x[k])

    return np.sqrt(8) * integral
コード例 #26
0
def Efficiency(l1, l2, T, N):
    """
    This function takes blah blah blah
    """
    #transform
    a = 1 - 1 / l1
    b = 1 - 1 / l2
    #Gaussian Quadrature
    x, w = gaussxwab(N, a, b)
    results = 0
    for i in range(N):
        results += w[i] * I(x[i], T)
    return results
コード例 #27
0
ファイル: gaussint.py プロジェクト: NatalieP-J/PHY407
def gaussint(fn, Nsamp, lowlim, uplim, args=False):
    """
	Returns the integral of fn from lowlim to uplim using Gaussian 
	quadrature with Nsamp sample points.

	"""
    x, w = gaussxwab(Nsamp, lowlim, uplim)  # gets points and weights
    s = 0.0  # start sum at zero
    for i in range(Nsamp):
        if args == False:
            s += w[i] * fn(x[i])  # evaluate fn at points and weight it
        elif args != False:
            s += w[i] * fn(x[i], args)  # evaluate fn at points and weight it
    return s
def integrator(f, a, b, N):
    """
    integrates f from a to b using Gaussian quadrature with N points, requires gaussxwab
    :param f: 1d function
    :param a: lower bound of domain
    :param b: upper bound of domain
    :param N: number of points
    :return:  floating value of integral
    """
    x, w = gaussxwab(N, a, b)
    integral = 0.0
    for k in range(N):
        integral += w[k] * f(x[k])

    return integral
コード例 #29
0
def c_v(T):
    c = 7.48279  # = 9V * rho * k_B in SI units
    theta_d = 428  # in K

    def f(x):
        return x**4 * exp(x) / (exp(x) - 1)**2

    # perform the integration using Gaussian quadrature
    n_points = 50
    x, w = gaussxwab(n_points, 0, theta_d / T)
    integral = 0.0
    for k in range(n_points):
        integral += w[k] * f(x[k])

    return c * (T / theta_d)**3 * integral
コード例 #30
0
def integrateBlackBodyComponent(x):
    
    # Calculate upperbound to use as minimum iteration.
    upperBoundX = np.log(1_000_000_000)
    
    # Assuming previous integral evaluating from 0 to 2 with 1000 (excessive) iterations.
    a = 0
    b = np.ceil(upperBoundX)*20 # Multiply to exceed upperbound even further.
    N = 1000
    
    # Calculate weights and integration points and sum.
    integrationPoints, weights = gaussxw.gaussxwab(N , a, b)
    result                     = (np.array(weights * f(integrationPoints))).sum()
    
    return result # ~6.4939394022668291
コード例 #31
0
def n(T):
    
    k = 1.38065e-23 # joules/kelvin
    c = 3e8 # meters/second
    
    N = 100
    a = h*c/(lam2*k*T)
    b = h*c/(lam1*k*T)
    x,w = gaussxwab(N,a,b)
    s = 0.0
        
    for k in range(N):
        s += w[k]*(x[k]**3/(exp(x[k])-1))
    
    s = s*(15/(pi*pi*pi*pi))
    return s
コード例 #32
0
def gauss_int(N, func1, func2):
    """
        Testing simple functions
        using gaussian integration:
        
        N   = order of accuracy of the integration - should match the order of the new D
                basis Dbasis function, or be higher - this shouldn't hurt but should
                be slower

        func1 = a function
        func2 = a function
    """

    #itegration interval
    a = 0.
    b = 1.

    # Calculate the sample vertices and weights, then map them
    # to the required integration domain
    #x,w = gaussxw(N)
    x, w = gaussxwab(N, a, b)
    #print 'x = {}'.format(x)
    #print 'w = {}'.format(w)
    """
        input:
            N = 
            a = min
            b = max
        returns integration vertices, x
        and
        integration weights, w
        mapped to the integral of a to b
    """

    # these are only used if you use the naive algorithm "gaussxw(N)"
    #xp = 0.5*(b-a)*x + 0.5*(b+a)
    #wp = 0.5*(b-a)*w
    #print 'x = {}; w = {}'.format(x,w)

    # Perform the integration
    s = 0.0
    for k in range(N):
        s += w[k] * func1(x[k]) * func2(x[k])
        #print 'k={}; x[{}] = {}, w[{}]={}'.format(k,k,x[k],k,w[k])
        #print 's={}'.format(s)
    #print 'for k = N={}, Final s={}'.format(k, s)
    return s
コード例 #33
0
def rms_x(n):
    """ INPUT: nth energy level
    
        OUTPUT: value of the root-mean-square position(x) """
    def rms_xintegrand(z):
        def x(z):
            return z / (1 - z)  #change of variables: equation 5.67

        return x(z)**2 * np.abs(psi(n, x(z)))**2 * (1 / (1 - z)**2
                                                    )  #integrand of <x>

    #integral of uncertainty of position
    I = 0.0
    N = 100
    a = 0
    b = 1
    x, w = gaussxwab(N, a, b)
    for k in range(N):
        I += w[k] * rms_xintegrand(x[k])
    return np.sqrt(2 * I)
コード例 #34
0
ファイル: intinf.py プロジェクト: KiMiralles/Python-Learning
from gaussxw import gaussxwab
from math import exp

def f(z):
    return exp(-z**2/(1-z)**2)/(1-z)**2

N = 50
a = 0.0
b = 1.0
x,w = gaussxwab(N,a,b)
s = 0.0
for k in range(N):
    s += w[k]*f(x[k])
print(s)
コード例 #35
0
# author: jiinso
# In Class Exercise 9
# 2014/9/30
# Gaussian Quadrature Integration

# Import the function gaussxwab from the module gaussxw
from gaussxw import gaussxwab

# Define the function to be integrated.
def f(x):
    return x**4 - 2*x + 1

# Set the N values and limits of integration a and b
# Note that the function guassxwab only integrates upto the N values 1000: do NOT set N higher than 1000.
N = 1000
a = 0
b = 2

# Call on the function gaussxwab to obtain x and c values.
x1, c1 = gaussxwab(N, a, b)

# Do a summation of the c(x1)* f(x1) for each number in range N.
S = 0.0
for i in range(N):
    S += c1[i] * f(x1[i])

# Print the summation out.
print ('The Gaussian Quadrature integration of this function is %2.20f. ' %S)
コード例 #36
0
ファイル: indep_q4.py プロジェクト: NatalieP-J/PHY407
from gaussxw import gaussxwab
import matplotlib.pyplot as plt

###############################################################################

# This code animates the temperature in a cylinder as a function of radius over
# time.

################################## CONSTANTS ##################################

Nint = 100 # Number of subintervals for Gaussian integration
b = np.pi # Upper bound of Bessel function integral
a = 0 # Lower bound of Bessel function integral

# Generate points and weights for Gaussian integration
taus,weights = gaussxwab(Nint,a,b)

# Set parameters for the cylinder
R = 10. # Radius of the cylinder
T0 = 50. # Initial temperature of the cylinder
c = 1.25 # Speed at which heat change propagates through the cylinder

################################## FUNCTIONS ##################################

def gaussint(fn,tau,w,args = False):
    """
    Returns the integral of fn from lowlim to uplim using Gaussian 
    quadrature with Nsamp sample points.
    """ 
    s = np.zeros(np.shape(args))
    for i in range(len(tau)):
コード例 #37
0
ファイル: indep_q3a.py プロジェクト: NatalieP-J/PHY407
import numpy as np
from scipy.special import jn_zeros
from gaussxw import gaussxwab

N = 100
b = np.pi
a = 0

taus,weights = gaussxwab(N,b,a)

def gaussint(fn,x,w,args = False):
    """
    Returns the integral of fn from lowlim to uplim using Gaussian 
    quadrature with Nsamp sample points.
    """ 
    s = np.zeros(np.shape(args))
    for i in range(len(x)):
        s += w[i]*fn(x[i],args) # evaluate fn at points and weight it
    return s

def J0int(tau,x):
    return np.cos(x*np.sin(tau))

def J0(x):
    return (1./np.pi)*gaussint(J0int,taus,weights,args = x)

def secant(initial,fn,tol):
    x1,x2 = initial
    while True:
        # Find slope of secant line connecting x1 and x2
        fprime = (fn(x2) - fn(x1))/(x2-x1) 
コード例 #38
0
# Rebecca Li
# In class exercise

from gaussxw import gaussxwab

#define the function we are going to integrate
def f(x):
    return x**4-2*x+1

N = 13   # N-th order Gaussian intergration 
a = 0    # Starting point
b = 2    # Ending point
x,w = gaussxwab(N,a,b) # Use the function gaussxwab to get the integration
                        # point x and its weight mapped to the interval [a,b]


I = 0  # Set the initial integral as 0
for i in range(N):   # Integrate
    I += f(x[i])*w[i]

print 'The intergral is %5.17f' %I