예제 #1
0
 def surfaceDensity(self, T):
     # Surface density at angle T
     x = T / self.Ts
     sigma = 2 * RHO_CRIT * self.delta_c * self.rs / (x**2 - 1) * (
         1 - 2 / csqrt(x**2 - 1) * np.arctan(csqrt((x - 1) / (x + 1))))
     if sigma.imag != 0: print(sigma.imag)
     return sigma.real
예제 #2
0
 def averageSurfaceDensity(self, T):
     # Average surface density at angle T
     x = T / self.Ts
     sigma_bar = 4 * RHO_CRIT * self.delta_c * self.rs / x**2 * (
         2 / csqrt(x**2 - 1) * np.arctan(csqrt(
             (x - 1) / (x + 1))) + np.log(x / 2))
     if sigma_bar.imag != 0: print(sigma_bar.imag)
     return sigma_bar.real
예제 #3
0
def py_cacos(z):
    # After CPython https://github.com/python/cpython/blob/e9e7d284c434768333fdfb53a3663eae74cb995a/Modules/cmathmodule.c#L237
    # Without the special cases
    # Implemented only because micropython is missing this function
    s1 = csqrt(1. - z.real - z.imag * 1.0j)
    s2 = csqrt(1. + z.real + z.imag * 1.0j)
    r = 2. * atan2(
        s1.real, s2.real) + asinh(s2.real * s1.imag - s2.imag * s1.real) * 1.0j
    return r
    def qr_aux(self, i, j):
        """递归对子矩阵进行QR迭代
        @param i: 子矩阵的左边界
        @param j: 子矩阵的右边界
        @return: Boolean
        """
        if j - i == 1:
            self.en[i] = self.a[i][i]
            return

        if j - i == 2:
            a = self.a[i][i]
            b = self.a[i][i + 1]
            c = self.a[i + 1][i]
            d = self.a[i + 1][i + 1]
            delta = (a + d) ** 2 - 4 * (a * d - b * c)

            if delta >= 0:
                self.en[i] = (a + d + sqrt(delta)) / 2
                self.en[i + 1] = (a + d - sqrt(delta)) / 2
            else:
                self.en[i] = (a + d + csqrt(delta)) / 2
                self.en[i + 1] = (a + d - csqrt(delta)) / 2
            return

        A = [[0 for _ in range(j - i)] for _ in range(j - i)]
        for x in range(j - i):
            for y in range(j - i):
                A[x][y] = self.a[i + x][i + y]

        for _ in range(50):
            for k in range(1, j - i):
                if abs(A[k][k - 1]) < 1e-9:
                    for x in range(j - i):
                        for y in range(j - i):
                            self.a[i + x][i + y] = A[x][y]

                    self.qr_aux(i, i + k)
                    self.qr_aux(i + k, j)
                    return False

            Q, R = self.qr_solve(A, j - i)
            A = multiply(R, Q)

        for k in range(i, j):
            self.en[k] = A[k - i][k - i]

        return False
예제 #5
0
def is_perfect_square(x, *, complex=False):
    complexType = type(1j)
    c = decimal.getcontext()

    if not complex:
        t = type(x)
        if not (t == int or t == float or t == decimal.Decimal):
            raise TypeError

        d = decimal.Decimal(x)

        if d < 0:
            result = False
        else:
            d.sqrt().to_integral_exact()
            if not c.flags[decimal.Inexact]:
                result = True
            else:
                result = False
    else:
        t = type(x)
        if not (t == int or t == float or t == complexType):
            raise TypeError

        y = csqrt(x)
        if y.real.is_integer() and y.imag.is_integer():
            result = True
        else:
            result = False

    c.clear_flags()

    return result
예제 #6
0
 def n(self, wl):
     e = 1.238 / wl
     er = 1 * self.einf
     for _A, _G, _E in zip(self.A, self.G, self.E):
         er += _A * _E * _G / (_E**2 - 1j * _G * e - e**2)
     n = csqrt(er)
     return n.real, n.imag
예제 #7
0
def acce_filtre_CP(vale_acce, dt, fcorner, amoc=1.0):
    # ---------------------------------------------------------
    # IN: f_in: ACCELEROGRAMME (signal temporel), pas dt
    #     fcorner: corner frequency (Hz),
    #     amoc: amortissement, l_freq: list of frequencies in Hz
    # OUT: f_out: ACCELEROGRAMME filtre (signal temporel),
    # attention: il faut de preference  2**N
    # ---------------------------------------------------------
    # CP filter/corner frequency : wcp
    wcp = fcorner * 2. * pi
    N = len(vale_acce)
    # discrectisation
    OM = pi / dt
    dw = 2. * OM / N
    N2 = N / 2 + 1
    ws0 = NP.arange(0.0, (N2 + 1) * dw, dw)
    ws = ws0[:N2]
    im = csqrt(-1)
    acce_in = NP.fft.fft(NP.array(vale_acce))
    hw2 = ws**2 * 1. / ((wcp**2 - ws**2) + 2. * amoc * im * wcp * ws)
    liste_pairs = zip(-hw2, acce_in[:N2])
    Yw = [a * b for a, b in liste_pairs]
    if is_even(N):  # nombre pair
        ni = 1
    else:  # nombre impair
        ni = 0
    for kk in range(N2 + 1, N + 1):
        Yw.append(Yw[N2 - ni - 1].conjugate())
        ni = ni + 1
    acce_out = NP.fft.ifft(Yw).real
    #      f_out = t_fonction(vale_t, acce_out, para=f_in.para)
    return acce_out
예제 #8
0
def new_quad(a, b, c):
	# Had the discriminant calculation broken into several steps, but checked,
	# and the precision was the same
	if (b**2 - (4 * a * c)) >= 0:
		discrim = sqrt(b**2 - (4 * a * c))
	else:
		discrim = csqrt(b**2 - (4 * a * c))  # If complex numbers are going to
											 # be involved

	pos_d_num = -b + discrim  # Adding the discriminant
	neg_d_num = -b - discrim  # Subtracting the discriminant
	denom = 2 * a

	numers = array([pos_d_num, neg_d_num])

	# Checking to see whether I will be dividing a very small number by another
	# small number

	for nn in range(len(numers)):
		if (abs(numers[nn]) < 0.1) and (abs(denom) < 1):
			# If this is true, it will use the other equation to calculate the
			# root instead
			replace = (2 * c) / numers[nn - 1]
			numers[nn] = replace
			# If not true, will simply divide by the normal denominator, 2*a
		else:
			numers[nn] /= denom

	return sort(numers)  # Going to return the roots from more negative to less
예제 #9
0
def complexvalue(z):
    det = ((z[1] * z[1]) - (4 * z[2] * z[0]))

    a = (-z[1] / (2 * z[2]))
    b = (csqrt(det) / (2 * z[2]))
    print("The roots are:")
    print(a + b, "and", a - b)
예제 #10
0
def quadSolver(a, b, c, p=1.0e-8):

    #check input parameters
    a = float(a)
    b = float(b)
    c = float(c)

    #not the quadratic case
    if abs(a) < p:

        #not a linear case
        if abs(b) < p:

            #infinite solutions
            if abs(c) < p:
                return (0, "infinit solutions")

            #no sulution
            else:
                return (0, "no solution available")

        #linear solution
        else:
            return (1, "linear case", -c / b)

    #quadratic case
    else:
        d = b**2 - 4 * a * c

        #real case
        if d > 0:
            from math import sqrt as rsqrt
            x1 = (-b + rsqrt(d)) / (2 * a)
            x2 = (-b - rsqrt(d)) / (2 * a)
            return (2, "real quadratic case", x1, x2)

        #complex case
        else:
            from cmath import sqrt as csqrt
            x1 = (-b + csqrt(d)) / (2 * a)
            x2 = (-b - csqrt(d)) / (2 * a)
            return (3, "complex quadratic case", x1, x2)

    return (-1, "case not implented!")
예제 #11
0
def quad(a, b, c):
    t = b**2 - 4 * a * c
    if t == 0:  # equations with one solution
        x = -b / (2.0 * a)
        x = '%2.f' % x
        real_.append(x)
        return real_
    elif t < 0:  # equations with complex solutions
        y = (-b + csqrt(t)) / (2.0 * a)
        z = (-b - csqrt(t)) / (2.0 * a)
        complex_.append(y)
        complex_.append(z)
        return complex_
    else:  # equations with real solutions
        y = (-b + rsqrt(t)) / (2.0 * a)
        z = (-b - rsqrt(t)) / (2.0 * a)
        real_.append(y)
        real_.append(z)
        return real_
예제 #12
0
def GammaComplex(z):
    z = complex(z)
    if z.real < 0.5:
        return pi / (csin(pi*z)*GammaComplex(1-z))
    else:
        z -= 1
        x = lanczos_coef[0] + \
            sum(lanczos_coef[i]/(z+i)
                for i in range(1, g+2))
        t = z + g + 0.5
        return csqrt(2*pi) * t**(z+0.5) * cexp(-t) * x
예제 #13
0
def DIPPR_EQ102_integral_by_T_over_T(T, a, b, c, d):
    """T-Integral of DPPR Equation #102 divided by T."""
    return (2 * a * T**(2 + b) * hyp2f1(1, 2 + b, 3 + b, -2 * T /
                                        (c - csqrt(c * c - 4 * d))) /
            ((2 + b) * (c - csqrt(c * c - 4 * d)) * csqrt(c * c - 4 * d)) -
            2 * a * T**(2 + b) * hyp2f1(1, 2 + b, 3 + b, -2 * T /
                                        (c + csqrt(c * c - 4 * d))) /
            ((2 + b) * (c + csqrt(c * c - 4 * d)) * csqrt(c * c - 4 * d))).real
예제 #14
0
def DIPPR_EQ102_integral_by_T(T, a, b, c, d):
    """T-Integral of DPPR Equation #102."""
    # imaginary part is 0
    return (2 * a * T**(3 + b) * hyp2f1(1, 3 + b, 4 + b, -2 * T /
                                        (c - csqrt(c * c - 4 * d))) /
            ((3 + b) * (c - csqrt(c * c - 4 * d)) * csqrt(c * c - 4 * d)) -
            2 * a * T**(3 + b) * hyp2f1(1, 3 + b, 4 + b, -2 * T /
                                        (c + csqrt(c * c - 4 * d))) /
            ((3 + b) * (c + csqrt(c * c - 4 * d)) * csqrt(c * c - 4 * d))).real
예제 #15
0
    def zeros(self):
        result = []
        for index, coefficients in enumerate(self):
            x = index - self.shift
            if len(coefficients) == 1 and coefficients[0] == 0:
                result.append(x)
            elif len(coefficients) == 2:
                zero = -coefficients[1] / coefficients[0]
                if 0 <= zero <= 1:
                    result.append(x + zero)
            elif len(coefficients) == 3:
                discriminant = coefficients[1] ** 2 - 4 * coefficients[0] * coefficients[2]
                if discriminant >= 0:
                    sqrt_d = sqrt(discriminant)
                    zero = (-coefficients[1] + sqrt_d) / (2 * coefficients[0])
                    if 0 <= zero <= 1:
                        result.append(x + zero)
                    if sqrt_d != 0:
                        zero = (-coefficients[1] - sqrt_d) / (2 * coefficients[0])
                        if 0 <= zero <= 1:
                            result.append(x + zero)
            elif len(coefficients) == 4 and False: #TODO: Fix
                a = coefficients[0]
                b = coefficients[1]
                c = coefficients[2]
                d = coefficients[3]

                #delta = 18 * a * b * c * d - 4 * b ** 3 * d + b ** 2 * c ** 2 - 4 * a * c ** 3 - 27 * a ** 2 * d ** 2

                delta0 = b ** 2 - 3 * a * c
                delta1 = 2 * b ** 3 - 9 * a * b * c + 27 * a ** 2 * d
                C = (0.5 * (delta1 + csqrt(delta1 ** 2 - 4 * delta0 ** 3))) ** (1 / 3)

                u1 = 1
                u2 = -0.5 + 1j * 0.8660254037844386j
                u3 = -0.5 + 1j * 0.8660254037844386j

                for u in [u1, u2, u3]:
                    zero = -1 / (3 * a) * (b + u * C + delta0 / (u * C))
                    if abs(zero.imag) < epsilon:
                        zero = zero.real
                        if 0 <= zero <= 1 and zero not in result:
                            result.append(x + zero)
            else:
                from frostsynth.numeric import zeros_in
                result.extend(zeros_in(self, x, x + 1))

        return result
예제 #16
0
def spherical_harmonic_real_scipy(l, m, theta, phi):
    """ real spherical harmonics of degree l and order m """
    # note that the definition of `sph_harm` has a different convention for the
    # usage of the variables phi and theta
    if m > 0:
        return (sph_harm(m, l, phi, theta) +
                (-1)**m * sph_harm(-m, l, phi, theta)
                ).real / math.sqrt(2)
        
    elif m == 0:
        return sph_harm(0, l, phi, theta).real
    
    else:  # m < 0
        return ((sph_harm(-m, l, phi, theta) -
                 (-1)**m * sph_harm(m, l, phi, theta)
                 ) / csqrt(-2)).real
def cubic_equation(a, b, c, d):
    p = (3 * a * c - b ** 2) / (3 * a ** 2)
    q = (2 * b ** 3 - 9 * a * b * c + 27 * a ** 2 * d) / (27 * a ** 3)
    Q = (p / 3) ** 3 + (q / 2) ** 2
    if Q >= 0:
        root = rect(sqrt(Q), 0)
    else:
        root = csqrt(Q)
    z = - q / 2 + root
    alpha = cube_root(abs(z))* rect(cos(phase(z) / 3), sin(phase(z) / 3))
    betha = -p/(3 * alpha)
    zed = sqrt(3) * (alpha - betha) / 2
    y_options = [alpha + betha,
         -(alpha + betha) / 2 + rect(-polar(zed)[1], polar(zed)[0]),
         -(alpha + betha) / 2 - rect(-polar(zed)[1], polar(zed)[0])]
    x = [str(y - b / (3 * a)) for y in y_options]
    return ','.join(x)
예제 #18
0
def is_perfect_square(number, *, complex=False) -> bool:
    if not complex:
        try:
            number = float(number)
        except ValueError:
            raise TypeError
        return simple_perfect_square(number)
    else:
        root = csqrt(number)
        if root.imag == 0:
            return root.real.is_integer()
        elif root.real == 0:
            return root.imag.is_integer()
        else:
            if root.real.is_integer():
                if root.imag.is_integer():
                    return True
    return False
예제 #19
0
def ACCE2SRO(f_in, xig, l_freq, ideb=2):
    # ---------------------------------------------------------
    # IN : f_in: ACCELEROGRAMME (signal temporel)
    #         xig: amortissement, l_freq: list of frequencies in Hz
    # OUT: f_out: SRO for l_freq (Hz)
    # attention: il faut de preference en 2**N
    # ---------------------------------------------------------
    para_sro = {
        'INTERPOL': ['LIN', 'LIN'],
        'NOM_PARA': 'FREQ',
        'PROL_DROITE': 'CONSTANT',
        'PROL_GAUCHE': 'EXCLU',
        'NOM_RESU': 'ACCE',
    }
    vale_t = f_in.vale_x
    vale_acce = f_in.vale_y
    N = len(vale_t)
    dt = vale_t[1] - vale_t[0]
    # discrectisation
    OM = pi / dt
    dw = 2. * OM / N
    N2 = N / 2 + 1
    ws0 = NP.arange(0.0, (N2 + 1) * dw, dw)
    ws = ws0[:N2]
    vale_sro = []
    im = csqrt(-1)
    acce_in = NP.fft.fft(NP.array(vale_acce))
    for fi in l_freq:
        w_0 = fi * 2. * pi
        hw2 = 1. / ((w_0**2 - ws**2) + 2. * xig * im * w_0 * ws)
        liste_pairs = zip(hw2, acce_in[:N2])
        Yw = [a * b for a, b in liste_pairs]
        if is_even(N):  # nombre pair
            ni = 1
        else:  # nombre impair
            ni = 0
        for kk in range(N2 + 1, N + 1):
            Yw.append(Yw[N2 - ni - 1].conjugate())
            ni = ni + 1
        acce_out = NP.fft.ifft(Yw).real
        vale_sro.append(w_0**ideb * max(abs(acce_out)))
    f_out = t_fonction(l_freq, vale_sro, para=para_sro)
    return f_out
예제 #20
0
    def n(self, wl):
        """Get the (complex) index of refraction at a specified wavelength (in um)

        Parameters
        ----------
        wl : float
            A wavelength value (in um) for which to return the index of refraction

        Returns
        -------
        n_re
            Real part of the index of refraction
        n_im
            Imaginary part of the index of refraction
        """
        e = 1.238 / wl
        er = 1 * self.einf
        for _A, _G, _E in zip(self.A, self.G, self.E):
            er += _A / (_E**2 - 1j * _G * e - e**2)
        n = csqrt(er)
        return n.real, n.imag
예제 #21
0
def polroots(p_in):
    p = p_in[:]
    res = {0: [], 1: []}
    try:
        while abs(p[-1]) < 1e-15:
            p.pop()
    except IndexError:
        return res  # zero polynomial
    while abs(p[0]) < 1e-15:
        p.pop(0)
        res[0] += [0]
    p = Pol(p)
    if len(p) == 1: return res
    if len(p) == 2:
        res[0] += [-p[0] / p[1]]
        return res
    while len(p) > 4:  # use Laguerre's method
        n, x, delta = len(p) - 1, 0, 1
        p1 = p_in.d()
        p2 = p1.d()
        for q in range(64):
            at = p(x)
            if abs(delta) < 1e-15 or abs(at) < 1e-15: break
            g = p1(x) / at
            h = g * g - p2(x) / at
            surd = csqrt((n - 1) * (n * h - g * g))
            d0, d1 = g + surd, g - surd
            delta = n / d0 if abs(d0) >= abs(d1) else n / d1
            x -= delta
        if abs(x.imag) < 1e-14:
            res[0] += [x.real]
            p = p.ruff(x.real)[1]
        else:
            res[1] += [x, x.conjugate()]
            p = p.qruff(x.real * x.real + x.imag * x.imag, -2 * x.real)
    if len(p) == 3: last = quadraticroots(*p)
    if len(p) == 4: last = cubicroots(*p)
    res[0] += last[0]
    res[1] += last[1]
    return res
예제 #22
0
                break
            else:
                print("Ups! Prueba de nuevo...")

    # Defino qué tipos de coeficientes voy a manejar
    vv = max(tip)

    ##########################################################################################
    if vv == 0:
        a = int(coeff[0])
        b = int(coeff[1])
        c = int(coeff[2])
        det = b**2 - 4 * a * c
        if det < 0:
            print('No tiene raíces reales')
            r1 = (-b - csqrt(complex(det))) / 2 / a
            r2 = (-b + csqrt(complex(det))) / 2 / a
            print('Las raíces son:\n--> x1 = ' + str(r1) + '\n--> x2 = ' +
                  str(r2))
        elif det == 0:
            print("Tiene raíces dobles...")
            r = -Fraction(b, 2 * a)
            if r.denominator == 1:
                r = r.numerator
                print('Las raíces son:\n--> x1 = x2 = ' + str(r))
            else:
                print('Las raíces son:\n--> x1 = x2 = ' + str(r.numerator) +
                      '/' + str(r.denominator))
        else:
            raiz = sqrt(det)
            print('Las raíces son:\n')
예제 #23
0
a=1
b=2
c=1

d=pow(b,2)-4*a*c

#WARUNKI
if d==0:
	print('x0 =',-b/2/a)
elif d>0:
	print('x1 =',-b-sqrt(d)/2/a)
	print('x2 =',-b+sqrt(d)/2/a)
else:
	#ZESPOLONE
	print('x1 =',-b-csqrt(d)/2/a)
	print('x2 =',-b+csqrt(d)/2/a)
	#c.real, c.imag

print()

#PĘTLE
for i in range(10,3,-2):
	print(i)

print()

l=[-7,100,3]
for i in l:
	i+=7
	print(i)
예제 #24
0
파일: matrix.py 프로젝트: 21zaber/MAI
 def norm_2(self):
     sum_pow_2 = 0
     for row in self.mtrx:
         sum_pow_2 += sum(map(lambda x: x**2, row))
     return sqrt(sum_pow_2) if type(sum_pow_2) is not complex else csqrt(sum_pow_2)
예제 #25
0
#There are several ways to import things from other libraries

from math import pi             #Pi is imported directly as a global variable
from math import sqrt           #Sqrt is imported
from cmath import sqrt as csqrt #Imports the sqrt function from cmath but
                                #renames it to prevent clashing functions
import math                     #This gives us access to all math.x functions
import math*                    #Imports every function from math

print pi
print math.e
print sqrt(4)
print csqrt(-1)
예제 #26
0
파일: dippr.py 프로젝트: CalebBell/thermo
def EQ102(T, A, B, C, D, order=0):
    r'''DIPPR Equation # 102. Used in calculating vapor viscosity, vapor
    thermal conductivity, and sometimes solid heat capacity. High values of B
    raise an OverflowError.
    All 4 parameters are required. C and D are often 0.

    .. math::
        Y = \frac{A\cdot T^B}{1 + \frac{C}{T} + \frac{D}{T^2}}

    Parameters
    ----------
    T : float
        Temperature, [K]
    A-D : float
        Parameter for the equation; chemical and property specific [-]
    order : int, optional
        Order of the calculation. 0 for the calculation of the result itself;
        for 1, the first derivative of the property is returned, for
        -1, the indefinite integral of the property with respect to temperature
        is returned; and for -1j, the indefinite integral of the property
        divided by temperature with respect to temperature is returned. No 
        other integrals or derivatives are implemented, and an exception will 
        be raised if any other order is given.

    Returns
    -------
    Y : float
        Property [constant-specific; if order == 1, property/K; if order == -1,
                  property*K; if order == -1j, unchanged from default]

    Notes
    -----
    The derivative with respect to T, integral with respect to T, and integral
    over T with respect to T are computed as follows. The first derivative is
    easily computed; the two integrals required Rubi to perform the integration.
    
    .. math::
        \frac{d Y}{dT} = \frac{A B T^{B}}{T \left(\frac{C}{T} + \frac{D}{T^{2}} 
        + 1\right)} + \frac{A T^{B} \left(\frac{C}{T^{2}} + \frac{2 D}{T^{3}}
        \right)}{\left(\frac{C}{T} + \frac{D}{T^{2}} + 1\right)^{2}}
        
    .. math::
        \int Y dT = - \frac{2 A T^{B + 3} \operatorname{hyp2f1}{\left (1,B + 3,
        B + 4,- \frac{2 T}{C - \sqrt{C^{2} - 4 D}} \right )}}{\left(B + 3\right) 
        \left(C + \sqrt{C^{2} - 4 D}\right) \sqrt{C^{2} - 4 D}} + \frac{2 A 
        T^{B + 3} \operatorname{hyp2f1}{\left (1,B + 3,B + 4,- \frac{2 T}{C 
        + \sqrt{C^{2} - 4 D}} \right )}}{\left(B + 3\right) \left(C 
        - \sqrt{C^{2} - 4 D}\right) \sqrt{C^{2} - 4 D}}
        
    .. math::
        \int \frac{Y}{T} dT = - \frac{2 A T^{B + 2} \operatorname{hyp2f1}{\left
        (1,B + 2,B + 3,- \frac{2 T}{C + \sqrt{C^{2} - 4 D}} \right )}}{\left(B 
        + 2\right) \left(C + \sqrt{C^{2} - 4 D}\right) \sqrt{C^{2} - 4 D}}
        + \frac{2 A T^{B + 2} \operatorname{hyp2f1}{\left (1,B + 2,B + 3,
        - \frac{2 T}{C - \sqrt{C^{2} - 4 D}} \right )}}{\left(B + 2\right) 
        \left(C - \sqrt{C^{2} - 4 D}\right) \sqrt{C^{2} - 4 D}}
        
    Examples
    --------
    Water vapor viscosity; DIPPR coefficients normally listed in Pa*s.

    >>> EQ102(300, 1.7096E-8, 1.1146, 0, 0)
    9.860384711890639e-06

    References
    ----------
    .. [1] Design Institute for Physical Properties, 1996. DIPPR Project 801
       DIPPR/AIChE
    '''
    if order == 0:
        return A*T**B/(1. + C/T + D/(T*T))
    elif order == 1:
        return (A*B*T**B/(T*(C/T + D/T**2 + 1)) 
                + A*T**B*(C/T**2 + 2*D/T**3)/(C/T + D/T**2 + 1)**2)
    elif order == -1:
        # imaginary part is 0
        return (2*A*T**(3+B)*hyp2f1(1, 3+B, 4+B, -2*T/(C - csqrt(C*C 
                - 4*D)))/((3+B)*(C - csqrt(C*C-4*D))*csqrt(C*C-4*D))
                -2*A*T**(3+B)*hyp2f1(1, 3+B, 4+B, -2*T/(C + csqrt(C*C - 4*D)))/(
                (3+B)*(C + csqrt(C*C-4*D))*csqrt(C*C-4*D))).real
    elif order == -1j:
        return (2*A*T**(2+B)*hyp2f1(1, 2+B, 3+B, -2*T/(C - csqrt(C*C - 4*D)))/(
                (2+B)*(C - csqrt(C*C-4*D))*csqrt(C*C-4*D)) -2*A*T**(2+B)*hyp2f1(
                1, 2+B, 3+B, -2*T/(C + csqrt(C*C - 4*D)))/((2+B)*(C + csqrt(
                C*C-4*D))*csqrt(C*C-4*D))).real
    else:
        raise Exception(order_not_found_msg)
예제 #27
0
def Z_from_virial_density_form(T, P, *args):
    r'''
    Calculates the compressibility factor of a gas given its temperature,
    pressure, and molar density-form virial coefficients. Any number of
    coefficients is supported.

    .. math::
        Z = \frac{PV}{RT} = 1 + \frac{B}{V} + \frac{C}{V^2} + \frac{D}{V^3}
        + \frac{E}{V^4} \dots

    Parameters
    ----------
    T : float
        Temperature, [K]
    P : float
        Pressure, [Pa]
    B to Z : float, optional
        Virial coefficients, [various]

    Returns
    -------
    Z : float
        Compressibility factor at T, P, and with given virial coefficients, [-]

    Notes
    -----
    For use with B or with B and C or with B and C and D, optimized equations 
    are used to obtain the compressibility factor directly.
    If more coefficients are provided, uses numpy's roots function to solve 
    this equation. This takes substantially longer as the solution is 
    numerical.
    
    If no virial coefficients are given, returns 1, as per the ideal gas law.
    
    The units of each virial coefficient are as follows, where for B, n=1, and
    C, n=2, and so on.
    
    .. math::
        \left(\frac{\text{m}^3}{\text{mol}}\right)^n

    Examples
    --------
    >>> Z_from_virial_density_form(300, 122057.233762653, 1E-4, 1E-5, 1E-6, 1E-7)
    1.2843496002100001

    References
    ----------
    .. [1] Prausnitz, John M., Rudiger N. Lichtenthaler, and Edmundo Gomes de 
       Azevedo. Molecular Thermodynamics of Fluid-Phase Equilibria. 3rd 
       edition. Upper Saddle River, N.J: Prentice Hall, 1998.
    .. [2] Walas, Stanley M. Phase Equilibria in Chemical Engineering. 
       Butterworth-Heinemann, 1985.
    
    '''
    l = len(args)
    if l == 1:
        return 1 / 2. + (4 * args[0] * P + R * T)**0.5 / (2 * (R * T)**0.5)


#       return ((R*T*(4*args[0]*P + R*T))**0.5 + R*T)/(2*P)
    elif l == 2:
        B, C = args
        # A small imaginary part is ignored
        return (
            P *
            (-(3 * B * R * T / P + R**2 * T**2 / P**2) /
             (3 * (-1 / 2 + csqrt(3) * 1j / 2) *
              (-9 * B * R**2 * T**2 / (2 * P**2) - 27 * C * R * T /
               (2 * P) + csqrt(-4 * (3 * B * R * T / P + R**2 * T**2 / P**2)**
                               (3 + 0j) +
                               (-9 * B * R**2 * T**2 / P**2 -
                                27 * C * R * T / P - 2 * R**3 * T**3 / P**3)**
                               (2 + 0j)) / 2 - R**3 * T**3 / P**3)**
              (1 / 3. + 0j)) - (-1 / 2 + csqrt(3) * 1j / 2) *
             (-9 * B * R**2 * T**2 / (2 * P**2) - 27 * C * R * T /
              (2 * P) + csqrt(-4 * (3 * B * R * T / P + R**2 * T**2 / P**2)**
                              (3 + 0j) +
                              (-9 * B * R**2 * T**2 / P**2 -
                               27 * C * R * T / P - 2 * R**3 * T**3 / P**3)**
                              (2 + 0j)) / 2 - R**3 * T**3 / P**3)**
             (1 / 3. + 0j) / 3 + R * T / (3 * P)) / (R * T)).real
    elif l == 3:
        # Huge mess. Ideally sympy could optimize a function for quick python
        # execution. Derived with kate's text highlighting
        B, C, D = args
        P2 = P**2
        RT = R * T
        BRT = B * RT
        T2 = T**2
        R2 = R**2
        RT23 = 3 * R2 * T2
        mCRT = -C * RT
        P2256 = 256 * P2

        RT23P2256 = RT23 / (P2256)
        big1 = (D * RT / P - (-BRT / P - RT23 / (8 * P2))**2 / 12 - RT *
                (mCRT / (4 * P) - RT * (BRT / (16 * P) + RT23P2256) / P) / P)
        big3 = (-BRT / P - RT23 / (8 * P2))
        big4 = (mCRT / P - RT * (BRT / (2 * P) + R2 * T2 / (8 * P2)) / P)
        big5 = big3 * (-D * RT / P + RT * (mCRT / (4 * P) - RT *
                                           (BRT /
                                            (16 * P) + RT23P2256) / P) / P)
        big2 = 2 * big1 / (
            3 *
            (big3**3 / 216 - big5 / 6 + big4**2 / 16 +
             csqrt(big1**3 / 27 +
                   (-big3**3 / 108 + big5 / 3 - big4**2 / 8)**2 / 4))**(1 / 3))
        big7 = 2 * BRT / (3 * P) - big2 + 2 * (
            big3**3 / 216 - big5 / 6 + big4**2 / 16 +
            csqrt(big1**3 / 27 +
                  (-big3**3 / 108 + big5 / 3 - big4**2 / 8)**2 / 4))**(
                      1 / 3) + R2 * T2 / (4 * P2)
        return (P * ((
            (csqrt(big7) / 2 +
             csqrt(4 * BRT / (3 * P) -
                   (-2 * C * RT / P - 2 * RT *
                    (BRT / (2 * P) + R2 * T2 /
                     (8 * P2)) / P) / csqrt(big7) + big2 - 2 *
                   (big3**3 / 216 - big5 / 6 + big4**2 / 16 +
                    csqrt(big1**3 / 27 +
                          (-big3**3 / 108 + big5 / 3 - big4**2 / 8)**2 / 4))**
                   (1 / 3) + R2 * T2 / (2 * P2)) / 2 + RT / (4 * P)))) / R /
                T).real

    args = list(args)
    args.reverse()
    args.extend([1, -P / R / T])
    solns = np.roots(args)
    rho = [i for i in solns if not i.imag and i.real > 0
           ][0].real  # Quicker than indexing where imag ==0
    return P / rho / R / T
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Pieter Huycke
email:   [email protected]
GitHub:  phuycke
"""

#%%

from cmath import sqrt as csqrt
from math import sqrt as msqrt

abc = str(input('Values for a,b and c (space separated)?\n'))
a, b, c = map(int, abc.split(' '))

if (b**2 - 4 * a * c) < 0:
    complex_root = csqrt((b**2 - 4 * a * c) + 0j)
    quad1, quad2 = -b + complex_root / 2 * a, -b - complex_root / 2 * a
    print('The roots are imaginary:\n{0}\n{1}'.format(quad1, quad2))
else:
    if msqrt(b**2 - 4 * a * c) == 0:
        print('There is only one solution:\n{}'.format(-b))
    else:
        quad1, quad2 = -b + msqrt(b**2 - 4 * a * c) / 2 * a, -b - msqrt(
            b**2 - 4 * a * c) / 2 * a
        print('There are two solutions:\n{0}\n{1}'.format(quad1, quad2))
예제 #29
0
def ghiggs(t):
    if t <= 1:
        return csqrt(1 - 1 / t) / 2. * (clog(
            (1 + csqrt(1 - 1 / t)) / (1 - csqrt(1 - 1 / t))) - pi * 1j)
    else:
        return csqrt(1 / t - 1) * casin(csqrt(t))
예제 #30
0
 def n(self, wl):
     n = csqrt(self.er(wl))
     return n.real, n.imag
예제 #31
0
파일: dippr.py 프로젝트: lilanyu/biosteam
def EQ102(T, A, B, C, D, order=0):
    r'''DIPPR Equation # 102. Used in calculating vapor viscosity, vapor
    thermal conductivity, and sometimes solid heat capacity. High values of B
    raise an OverflowError.
    All 4 parameters are required. C and D are often 0.

    .. math::
        Y = \frac{A\cdot T^B}{1 + \frac{C}{T} + \frac{D}{T^2}}

    Parameters
    ----------
    T : float
        Temperature, [K]
    A-D : float
        Parameter for the equation; chemical and property specific [-]
    order : int, optional
        Order of the calculation. 0 for the calculation of the result itself;
        for 1, the first derivative of the property is returned, for
        -1, the indefinite integral of the property with respect to temperature
        is returned; and for -1j, the indefinite integral of the property
        divided by temperature with respect to temperature is returned. No 
        other integrals or derivatives are implemented, and an exception will 
        be raised if any other order is given.

    Returns
    -------
    Y : float
        Property [constant-specific; if order == 1, property/K; if order == -1,
                  property*K; if order == -1j, unchanged from default]

    Notes
    -----
    The derivative with respect to T, integral with respect to T, and integral
    over T with respect to T are computed as follows. The first derivative is
    easily computed; the two integrals required Rubi to perform the integration.
    
    .. math::
        \frac{d Y}{dT} = \frac{A B T^{B}}{T \left(\frac{C}{T} + \frac{D}{T^{2}} 
        + 1\right)} + \frac{A T^{B} \left(\frac{C}{T^{2}} + \frac{2 D}{T^{3}}
        \right)}{\left(\frac{C}{T} + \frac{D}{T^{2}} + 1\right)^{2}}
        
    .. math::
        \int Y dT = - \frac{2 A T^{B + 3} \operatorname{hyp2f1}{\left (1,B + 3,
        B + 4,- \frac{2 T}{C - \sqrt{C^{2} - 4 D}} \right )}}{\left(B + 3\right) 
        \left(C + \sqrt{C^{2} - 4 D}\right) \sqrt{C^{2} - 4 D}} + \frac{2 A 
        T^{B + 3} \operatorname{hyp2f1}{\left (1,B + 3,B + 4,- \frac{2 T}{C 
        + \sqrt{C^{2} - 4 D}} \right )}}{\left(B + 3\right) \left(C 
        - \sqrt{C^{2} - 4 D}\right) \sqrt{C^{2} - 4 D}}
        
    .. math::
        \int \frac{Y}{T} dT = - \frac{2 A T^{B + 2} \operatorname{hyp2f1}{\left
        (1,B + 2,B + 3,- \frac{2 T}{C + \sqrt{C^{2} - 4 D}} \right )}}{\left(B 
        + 2\right) \left(C + \sqrt{C^{2} - 4 D}\right) \sqrt{C^{2} - 4 D}}
        + \frac{2 A T^{B + 2} \operatorname{hyp2f1}{\left (1,B + 2,B + 3,
        - \frac{2 T}{C - \sqrt{C^{2} - 4 D}} \right )}}{\left(B + 2\right) 
        \left(C - \sqrt{C^{2} - 4 D}\right) \sqrt{C^{2} - 4 D}}
        
    Examples
    --------
    Water vapor viscosity; DIPPR coefficients normally listed in Pa*s.

    >>> EQ102(300, 1.7096E-8, 1.1146, 0, 0)
    9.860384711890639e-06

    References
    ----------
    .. [1] Design Institute for Physical Properties, 1996. DIPPR Project 801
       DIPPR/AIChE
    '''
    if order == 0:
        return A * T**B / (1. + C / T + D / (T * T))
    elif order == 1:
        return (A * B * T**B / (T * (C / T + D / T**2 + 1)) + A * T**B *
                (C / T**2 + 2 * D / T**3) / (C / T + D / T**2 + 1)**2)
    elif order == -1:
        # imaginary part is 0
        return (
            2 * A * T**(3 + B) * hyp2f1(1, 3 + B, 4 + B, -2 * T /
                                        (C - csqrt(C * C - 4 * D))) /
            ((3 + B) * (C - csqrt(C * C - 4 * D)) * csqrt(C * C - 4 * D)) -
            2 * A * T**(3 + B) * hyp2f1(1, 3 + B, 4 + B, -2 * T /
                                        (C + csqrt(C * C - 4 * D))) /
            ((3 + B) * (C + csqrt(C * C - 4 * D)) * csqrt(C * C - 4 * D))).real
    elif order == -1j:
        return (
            2 * A * T**(2 + B) * hyp2f1(1, 2 + B, 3 + B, -2 * T /
                                        (C - csqrt(C * C - 4 * D))) /
            ((2 + B) * (C - csqrt(C * C - 4 * D)) * csqrt(C * C - 4 * D)) -
            2 * A * T**(2 + B) * hyp2f1(1, 2 + B, 3 + B, -2 * T /
                                        (C + csqrt(C * C - 4 * D))) /
            ((2 + B) * (C + csqrt(C * C - 4 * D)) * csqrt(C * C - 4 * D))).real
    else:
        raise Exception(order_not_found_msg)
예제 #32
0
파일: modules.py 프로젝트: mtist/c201702
import random
from math import sin, sqrt
# from cmath import *
from cmath import sqrt as csqrt
import qeq
import wave
import pyglet

best_men = ["Рукижат", "Магомед"]
print(random.choice(best_men))
print(sin(3))
print(sqrt(4))
print(csqrt(-1))
# wave.open("aaaaa.wav", mode=None)

song = pyglet.media.load('aaaaa.ogg')
song.play()
pyglet.app.run()
a, b, c = input("Введите коэффиценты a, b, c ").split(" ")
a, b, c = int(a), int(b), int(c)
print(qeq.solve(a, b, c))
예제 #33
0
a = float(input("a= "))
b = float(input("b= "))
c = float(input("c= "))
delta = b * b - 4 * a * c
if delta < 0:
    print("brak rozwiazan rzeczywistych")
elif delta == 0:
    print("wynik to")
    print(-b / 2 * a)
else:
    print("wynik to")
    print(((-1) * b - sqrt(delta) / 2 * a, "lub",
           ((-1) * b + sqrt(delta) / 2 * a)))

print((-b - csqrt(delta) / 2 * a, "lub", (-b + csqrt(delta) / 2 * a)))
print('////////////działa jak w C2/////////////////////////')
from sys import argv
print(argv)
print('/////////////////////////////////////')
for i in range(10, 3, -2):
    print(i)
print('/////////////////////////////////////')
for i in range(len(nowa_nowa_lista)):
    nowa_nowa_lista[i] = 1
print(nowa_nowa_lista)

print('/////////////////////////////////////')
lista2 = ([1, 2], (3, 4), [5, 6])
for i, j in lista2:
    if i + j > 20:
예제 #34
0
def ghiggs(t):
    if t<=1:
        return csqrt(1-1/t)/2. * ( clog((1 + csqrt(1-1/t))/(1 - csqrt(1-1/t)))-pi*1j)
    else:
        return csqrt(1/t-1)*casin(csqrt(t))
예제 #35
0
def gmp(z, q, sigma2, lambdaN):
    lamb = lambdaN * ((1 + csqrt(q)) / (1 - csqrt(q)))
    g = (z + sigma2 *
         (q - 1) - csqrt(z - lambdaN) * csqrt(z - lamb)) / (2 * q * z * sigma2)
    return g