def zddim(self, w): """Given a dimensionless frequency, returns the bulk diffusion impedance depending on the dimensionality of the particles""" # Threshold to use for high freq approximations w_high = 5000 # parameters used in following equations a = sqrt(j * w) b = sqrt(2 * j * w) if self.n == 1: if w < w_high: return (a * tanh(a)) ** -1 else: # This is a high frequency approximation return b ** -1 * (1 - j) elif self.n == 2: if w < w_high: return I(0, a) / (a * I(1, a)) else: # This is a high frequency approximation return b ** -1 * (1 - j) - j * b ** -1 elif self.n == 3: if w < w_high: return tanh(a) / (a - tanh(a)) else: # This is a high frequency approximation return b ** -1 * (1 - j) - j * w ** -1
def calculosTrigonometricos(z): """ calcuar_func_tr(numero_complejo) -> [sen(z), cos(z), tan(z), csc(z), sec(z), cot(z), senh(z), cos(z), tan(z)] Devuelve una lista con los resultados de aplicar funciones trigonométricas a un número complejo Argumento: z: numero complejo """ resultados = [] resultados.append(cmath.sin(z)) resultados.append(cmath.cos(z)) resultados.append(cmath.tan(z)) resultados.append(cmplxcsc(z)) resultados.append(cmplxsec(z)) resultados.append(cmplxcot(z)) resultados.append(cmath.sinh(z)) resultados.append(cmath.cosh(z)) resultados.append(cmath.tanh(z)) return resultados
def f(x): return (20 * cmath.log10( abs( cmath.cosh((complex( (math.sqrt(math.pi * x * mur * 4 * math.pi * math.pow( 10, -7) * sigma)) * math.cos(math.pi / 4), (math.sqrt(math.pi * x * mur * 4 * math.pi * math.pow( 10, -7) * sigma)) * math.sin(math.pi / 4))) * h)) ) + 20 * cmath.log10( abs(1 + 0.5 * ((complex(0, -k * x * radius)) / (complex( (math.sqrt(math.pi * x * mur * 4 * math.pi * math.pow( 10, -7) / sigma)) * math.cos(math.pi / 4), (math.sqrt(math.pi * x * mur * 4 * math.pi * math.pow( 10, -7) / sigma)) * math.sin(math.pi / 4))) + (complex( (math.sqrt(math.pi * x * mur * 4 * math.pi * math.pow( 10, -7) / sigma)) * math.cos(math.pi / 4), (math.sqrt(math.pi * x * mur * 4 * math.pi * math.pow( 10, -7) / sigma)) * math.sin(math.pi / 4))) / (complex(0, -k * x * radius))) * cmath.tanh((complex( (math.sqrt(math.pi * x * mur * 4 * math.pi * math.pow( 10, -7) * sigma)) * math.cos(math.pi / 4), (math.sqrt(math.pi * x * mur * 4 * math.pi * math.pow( 10, -7) * sigma)) * math.sin(math.pi / 4))) * h))) ).real
def Heston_cf(self, u): """ Define a function that computes the characteristic function for variance gamma """ sigma = self.sigma eta0 = self.eta0 kappa = self.kappa rho = self.rho theta = self.theta S0 = self.S0 r = self.r T = self.T q = self.q ii = complex(0, 1) l = cmath.sqrt(sigma**2 * (u**2 + ii * u) + (kappa - ii * rho * sigma * u)**2) w = np.exp(ii * u * np.log(S0) + ii * u * (r - q) * T + kappa * theta * T * (kappa - ii * rho * sigma * u) / sigma**2) / ( cmath.cosh(l * T / 2) + (kappa - ii * rho * sigma * u) / l * cmath.sinh(l * T / 2))**(2 * kappa * theta / sigma**2) y = w * np.exp( -(u**2 + ii * u) * eta0 / (l / cmath.tanh(l * T / 2) + kappa - ii * rho * sigma * u)) return y
def Heston_cf(self, u): sigma = self.sigma kappa = self.kappa rho = self.rho S0 = self.S0 r = self.r T = self.T theta = self.theta v0 = self.v0 ii = complex(0, 1) lmbd = cmath.sqrt(sigma**2 * (u**2 + ii * u) + (kappa - ii * rho * sigma * u)**2) w_nume = np.exp(ii * u * np.log(S0) + ii * u * (r - self.q) * T + kappa * theta * T * (kappa - ii * rho * sigma * u) / sigma**2) w_deno = (cmath.cosh(lmbd * T / 2) + (kappa - ii * rho * sigma * u) / lmbd * cmath.sinh(lmbd * T / 2))**(2 * kappa * theta / sigma**2) w = w_nume / w_deno y = w * np.exp( -(u**2 + ii * u) * v0 / (lmbd / cmath.tanh(lmbd * T / 2) + kappa - ii * rho * sigma * u)) return y
def _find_subtree_new_diam_in_cm(root_input_impedance, electrotonic_length_as_complex, rm, ra, q): '''finds the subtree's new cable's diameter (in cm) according to the given complex input impedance at the segment in the original subtree that is closest to the soma (the tip), and the given cable electrotonic length, with the following equation: d (in cm) = (2/PI * (sqrt(RM*RA)/(q*subtree_root_input_impedance)) * (coth(q * NewCableElectrotonicLength)) )^(2/3) derived from Rall's cable theory for dendrites (Gal Eliraz) ''' diam_in_cm = ( 2.0 / math.pi * (math.sqrt(rm * ra) / (q * root_input_impedance)) * (1 / cmath.tanh(q * electrotonic_length_as_complex)) # coth = 1/tanh )**(2.0 / 3) ''' # for debugging inaccuracies: if diam_in_cm.imag != 0: if abs(diam_in_cm.imag) > 0.03: print "PROBLEM - DIAM HAS SUBSTANTIAL IMAGINARY PART" print "\n" ''' # the radius of the complex number received from the equation new_subtree_dend_diam_in_cm = cmath.polar(diam_in_cm)[0] return new_subtree_dend_diam_in_cm
def op_tanh(x): """Returns the hyperbolic tangent of this mathematical object.""" if isinstance(x, list): return [op_tanh(a) for a in x] elif isinstance(x, complex): return cmath.tanh(x) else: return math.tanh(x)
def TL_length(b, length, resistance_R, inductance_L, capacitance_C, conductance_G): f = 60 if length < 80: print('The transmission line is a short line') print('Shunt effects are neglected') z = complex(resistance_R / b, (2 * math.pi * f * inductance_L)) y = 0 print('z =', z) print('y =', y) Z = length * complex(resistance_R / b, (2 * math.pi * f * inductance_L)) Y = 0 Zc = 0 g = 0 gl = 0 gphi = 0 zphi = 0 elif 80 < length and length < 240: print('The transmission line is a medium line') z = complex(resistance_R / b, (2 * math.pi * f * inductance_L)) y = complex(0, (2 * math.pi * f * capacitance_C)) Z = length * complex(resistance_R / b, (2 * math.pi * f * inductance_L)) Y = length * complex(0, (2 * math.pi * f * capacitance_C)) print('z =', z) print('y =', y) Zc = 0 g = 0 gl = 0 gphi = 0 zphi = 0 else: print('The transmission line is a long line') z = complex(resistance_R / b, (2 * math.pi * f * inductance_L)) y = complex(0, (2 * math.pi * f * capacitance_C)) print('z =', z) print('y =', y) gphi = (cmath.phase(z) + (cmath.phase(y))) / 2 print('gphi = ', gphi) zphi = (cmath.phase(z) - (cmath.phase(y))) / 2 print('zphi =', zphi) g = cmath.rect(math.sqrt(abs(z) * abs(y)), gphi) gl = g * length print('gl =', gl) print('g= ', g) Zc = cmath.rect(math.sqrt(abs(z) / abs(y)), zphi) print('Zc =', Zc) Z = Zc * cmath.sinh(gl) print('Z =', Z) Y1 = (1 / Zc) * cmath.tanh(gl / 2) print('Y1', Y1) Y = 2 * Y1 return Z, Y, Zc, gl, g, gphi, zphi, z, y
def pieq(self, z, y): d = self.line_length gamma = cmath.sqrt(z*y) Zc = cmath.sqrt(z/y) Z_pi = Zc * cmath.sinh(gamma*d) Y_pi = 1.0/Zc * cmath.tanh(gamma*d/2.0) # The real part of Y_pi is different from TLC.for, but # the real part isn't important return Z_pi, Y_pi
def tanh(self): comp_value = cmath.tanh(self.comp_value) dx1 = 1 - cmath.cosh(2 * self.comp_value) dx2 = 1 + cmath.cosh(2 * self.comp_value) dx3 = dx1 * dx2 dxr = dx3 / 4 dxrf = (1 - dxr) comp_unc = self.comp_unc * dxrf # if y = tanhx than U(y) = U(x)(1-tanh^2x) return Ucom(comp_value, comp_unc, self.name, self.dep)
def p_sine(t): '''e : SINE LP e RP | COSINE LP e RP | SECANT LP e RP | COSECANT LP e RP | TANGENT LP e RP | COTANGENT LP e RP | LOG LP e COMMA e RP | LN LP e RP | EXP POW LP e RP | ARCSINE LP e RP | ARCCOSINE LP e RP | ARCTANGENT LP e RP | SINEH LP e RP | COSINEH LP e RP | TANGENTH LP e RP | ARCSINEH LP e RP | ARCCOSINEH LP e RP | ARCTANGENTH LP e RP ''' if t[1] == 'sin': t[0] = cmath.sin(t[3]) elif t[1] == 'cos': t[0] = cmath.cos(t[3]) elif t[1] == 'sec': t[0] = 1/cmath.cos(t[3]) elif t[1] == 'cosec': t[0] = 1/cmath.sin(t[3]) elif t[1] == 'tan': t[0] = cmath.tan(t[3]) elif t[1] == 'cot': t[0] = 1/cmath.tan(t[3]) elif t[1] == 'log': t[0] = cmath.log(t[3], t[5]) elif t[1] == 'ln': t[0] = cmath.log(t[3], cmath.e) elif t[1] == 'e': t[0] = cmath.exp(t[4]) elif t[1] == 'asin': t[0] = cmath.asin(t[3]) elif t[1] == 'acos': t[0] = cmath.acos(t[3]) elif t[1] == 'atan': t[0] = cmath.atan(t[3]) elif t[1] == 'sinh': t[0] = cmath.sinh(t[3]) elif t[1] == 'cosh': t[0] = cmath.cosh(t[3]) elif t[1] == 'tanh': t[0] = cmath.tanh(t[3]) elif t[1] == 'asinh': t[0] = cmath.asinh(t[3]) elif t[1] == 'acosh': t[0] = cmath.acosh(t[3]) elif t[1] == 'atanh': t[0] = cmath.atanh(t[3])
def tanh(*args, **kw): arg0 = args[0] if isinstance(arg0, (int, float, long)): return _math.tanh(*args,**kw) elif isinstance(arg0, complex): return _cmath.tanh(*args,**kw) elif isinstance(arg0, _sympy.Basic): return _sympy.tanh(*args,**kw) else: return _numpy.tanh(*args,**kw)
def test_tanh_cc (self): src_data = [complex(i,i+1) for i in range(-5, 5, 2)] expected_result = tuple(cmath.tanh(i) for i in src_data) src = gr.vector_source_c(src_data) op = gr.transcendental('tanh', 'complex_float') snk = gr.vector_sink_c() self.tb.connect(src, op, snk) self.tb.run() result = snk.data() self.assertComplexTuplesAlmostEqual(expected_result, result, places=5)
def ERRSTP(H, d, L): if np.isclose(L, 0.0): steep = float('inf') k = float('inf') else: steep = H / L k = (2.0 * math.pi) / L maxstp = 0.142 * cmath.tanh(k * d) return steep, maxstp
def get_d_ex(freq_ex, time): tau_ex = 1j * time d_mat = np.zeros((freq_ex.shape[0], freq_ex.shape[0]), dtype=np.complex_) counter = 0 while counter < freq_ex.shape[0]: d_mat[counter, counter] = freq_ex[counter] * cmath.tanh( freq_ex[counter] * tau_ex / 2.0) counter = counter + 1 return d_mat
def get_c_gs(freq_gs, kBT, time): tau_gs = -1j * time + 1.0 / kBT c_mat = np.zeros((freq_gs.shape[0], freq_gs.shape[0]), dtype=np.complex_) counter = 0 while counter < freq_gs.shape[0]: c_mat[counter, counter] = freq_gs[counter] * 1.0 / cmath.tanh( freq_gs[counter] * tau_gs / 2.0) counter = counter + 1 return c_mat
def get_c_ex(freq_ex, time): tau_ex = time c_mat = np.zeros((freq_ex.shape[0], freq_ex.shape[0]), dtype=np.complex_) counter = 0 while counter < freq_ex.shape[0]: c_mat[counter, counter] = freq_ex[counter] * 1.0 / cmath.tanh( freq_ex[counter] * tau_ex / 2.0) counter = counter + 1 return c_mat
def costf(sol): newsol = changedomain(domain, newdomain, sol) d = newsol[0] * 1e-3 epsr = newsol[1] epsf = newsol[2] w = 2 * math.pi * newsol[3] * 1e9 EPS = epsr - 1j * epsf gamma = 1j * w / c * cmath.sqrt(EPS) Zf = Z0 / cmath.sqrt(EPS) * cmath.tanh(gamma * d) return abs((Zf - Z0) / (Zf + Z0))**2
def sherwood_tanh(x): try: n = len(x) except TypeError: x = np.array([x]) n = 1 f = np.zeros(n, dtype=complex) for i in range(n): f[i] = cmath.sqrt(x[i]) * cmath.tanh(cmath.sqrt(x[i])) return f
def TANH(df, price='Close'): """ Hyperbolic Tangent """ tanh_list = [] i = 0 while i < len(df[price]): tanh = cmath.tanh(df[price][i]).real tanh_list.append(tanh) i += 1 return tanh_list
def tanh(z): """ An AlComplex compatible hyperbolic tangent function. Parameters ---------- z : Python numeric type or AlComplex Returns ------- AlComplex """ return AlComplex.from_python_complex(cm.tanh(z.to_python_complex()))
def test_complex_functions(): for x in (list(range(10)) + list(range(-10, 0))): for y in (list(range(10)) + list(range(-10, 0))): z = complex(x, y) / 4.3 + 0.01j assert exp(mpc(z)).ae(cmath.exp(z)) assert log(mpc(z)).ae(cmath.log(z)) assert cos(mpc(z)).ae(cmath.cos(z)) assert sin(mpc(z)).ae(cmath.sin(z)) assert tan(mpc(z)).ae(cmath.tan(z)) assert sinh(mpc(z)).ae(cmath.sinh(z)) assert cosh(mpc(z)).ae(cmath.cosh(z)) assert tanh(mpc(z)).ae(cmath.tanh(z))
def test_complex_functions(): for x in (list(range(10)) + list(range(-10,0))): for y in (list(range(10)) + list(range(-10,0))): z = complex(x, y)/4.3 + 0.01j assert exp(mpc(z)).ae(cmath.exp(z)) assert log(mpc(z)).ae(cmath.log(z)) assert cos(mpc(z)).ae(cmath.cos(z)) assert sin(mpc(z)).ae(cmath.sin(z)) assert tan(mpc(z)).ae(cmath.tan(z)) assert sinh(mpc(z)).ae(cmath.sinh(z)) assert cosh(mpc(z)).ae(cmath.cosh(z)) assert tanh(mpc(z)).ae(cmath.tanh(z))
def do_transfer_function(length,freq,type=3, measure="m"): ''' Let the transfer function default to type 3; Allows for easy default change later Allows for easy 'case-based' changes ''' ''' Z=impedance/l, Y=admittance/l Z=R+jwL, Y=G+jwC Z0=Characteristic Impedence, gamma=propagation constant Z0=sqrt(Z/Y), gamma=sqrt(Z*Y) Should Use PyGSL, but start off with cmath ''' #Length must be in KM if measure == "m": length /= 1000 elif measure == "km": pass else: raise TypeError('Improper measurement scale used') w = 2 * pi * freq #log.debug("Freq=%f,Len=%d",freq,length) Z = complex(_R(freq),w*_L(freq)) Y = complex(_G(freq),w*_C(freq)) Z0 = cmath.sqrt(Z/Y) gamma = cmath.sqrt(Z*Y) gammad=gamma*length Zs = complex(100,0) Zl = complex(100,0) upper = Z0 * ( 1/cmath.cosh(gammad)) #sech=1/cosh lower = Zs * ( (Z0/Zl) + cmath.tanh(gammad) ) + Z0 * ( 1+ (Z0/Zl)*cmath.tanh(gammad) ) H = upper/lower H*=H return cmath.polar(H)[0] #polar returns (abs(h),real(h))
def oneArgFuncEval(function, value): # Evaluates functions that take a complex number input if function == "sin": return cmath.sin(value) elif function == "cos": return cmath.cos(value) elif function == "tan": return cmath.tan(value) elif function == "asin": return cmath.asin(value) elif function == "acos": return cmath.acos(value) elif function == "atan": return cmath.atan(value) elif function == "csc": return 1.0 / cmath.sin(value) elif function == "sec": return 1.0 / cmath.cos(value) elif function == "cot": return 1.0 / cmath.tan(value) elif function == "ln": return cmath.log(value) elif function == "sqr": return cmath.sqrt(value) elif function == "abs": return cmath.sqrt((value.real**2) + (value.imag**2)) elif function == "exp": return cmath.exp(value) if function == "sinh": return cmath.sinh(value) elif function == "cosh": return cmath.cosh(value) elif function == "tanh": return cmath.tanh(value) elif function == "asinh": return cmath.asinh(value) elif function == "acosh": return cmath.acosh(value) elif function == "atanh": return cmath.atanh(value) elif function == "ceil": return math.ceil(value.real) + complex(0, 1) * math.ceil(value.imag) elif function == "floor": return math.floor(value.real) + complex(0, 1) * math.floor(value.imag) elif function == "trunc": return math.trunc(value.real) + complex(0, 1) * math.trunc(value.imag) elif function == "fac": if value.imag == 0 and value < 0 and value.real == int(value.real): return "Error: The factorial function is not defined on the negative integers." return gamma(value + 1) elif function == "log": return cmath.log10(value)
def oneArgFuncEval(function, value): # Evaluates functions that take a complex number input if function == "sin": return cmath.sin(value) elif function == "cos": return cmath.cos(value) elif function == "tan": return cmath.tan(value) elif function == "asin": return cmath.asin(value) elif function == "acos": return cmath.acos(value) elif function == "atan": return cmath.atan(value) elif function == "csc": return 1.0 / cmath.sin(value) elif function == "sec": return 1.0 / cmath.cos(value) elif function == "cot": return 1.0 / cmath.tan(value) elif function == "ln": return cmath.log(value) elif function == "sqr": return cmath.sqrt(value) elif function == "abs": return cmath.sqrt((value.real ** 2) + (value.imag ** 2)) elif function == "exp": return cmath.exp(value) if function == "sinh": return cmath.sinh(value) elif function == "cosh": return cmath.cosh(value) elif function == "tanh": return cmath.tanh(value) elif function == "asinh": return cmath.asinh(value) elif function == "acosh": return cmath.acosh(value) elif function == "atanh": return cmath.atanh(value) elif function == "ceil": return math.ceil(value.real) + complex(0, 1) * math.ceil(value.imag) elif function == "floor": return math.floor(value.real) + complex(0, 1) * math.floor(value.imag) elif function == "trunc": return math.trunc(value.real) + complex(0, 1) * math.trunc(value.imag) elif function == "fac": if value.imag == 0 and value < 0 and value.real == int(value.real): return "Error: The factorial function is not defined on the negative integers." return gamma(value + 1) elif function == "log": return cmath.log10(value)
def mim_disp(beta, k_0, eps_1, eps_2, w, even_H_parity=True, full_output=False): '''Exact MIM dispersion relation from [3] Find Beta by finding the zeros of the function with the Newton-Raphson process''' k1 = cm.sqrt(beta**2 - eps_1 * k_0**2) k2 = cm.sqrt(beta**2 - eps_2 * k_0**2) if even_H_parity: ze = cm.tanh(k2 * w / 2) + k1 * eps_2 / (eps_1 * k2) else: ze = cm.tanh(k2 * w / 2) + (eps_1 * k2) / (k1 * eps_2) if not (full_output): return ze else: return k1, k2
def coth(x): """ coth function for scalar or array argument """ if np.isscalar(x): if(x == 0): val = np.inf else: val = 1. / cmath.tanh(x) else: shape = x.shape x = np.ravel(x) val = np.zeros(len(x), dtype=np.complex128) for i in np.arange(len(x)): tan_hyp = cmath.tanh(x[i]) if(tan_hyp == 0): val[i] = np.inf else: val[i] = 1. / tan_hyp val = val.reshape(shape) if np.iscomplexobj(x): return val else: return val.real
def coth(x): """ coth function for scalar or array argument """ if np.isscalar(x): if (x == 0): val = np.inf else: val = 1. / cmath.tanh(x) else: shape = x.shape x = np.ravel(x) val = np.zeros(len(x), dtype=np.complex128) for i in np.arange(len(x)): tan_hyp = cmath.tanh(x[i]) if (tan_hyp == 0): val[i] = np.inf else: val[i] = 1. / tan_hyp val = val.reshape(shape) if np.iscomplexobj(x): return val else: return val.real
def construct(self): dots = [] for i in range(100): for j in range(100): c = cmath.sin(0.1*i+0.1*j*1j) - 2 d = (c.real**2+c.imag**2)*0.5 sc = cmath.tanh(abs(d)) dots.append(Square(color=RED, opacity=sc, side_length=0.01) .move_to(i*0.1*RIGHT+j*0.1*UP)) gps = VGroup(*dots).move_to(ORIGIN) self.add(gps) self.wait()
def gamma(grid): f = grid[0] d = grid[1] # I know, it's super ugly. y = (20 * cmath.log10( (abs(((1 * (cmath.sqrt((mu1f(f) - j * mu2f(f)) / (e1f(f) - cmath.sqrt(-1) * e2f(f)))) * (cmath.tanh(j * (2 * cmath.pi * (f * 10**9) * (d * 0.001) / 299792458) * cmath.sqrt( (mu1f(f) - j * mu2f(f)) * (e1f(f) - j * e2f(f)))))) - 1) / ((1 * (cmath.sqrt( (mu1f(f) - j * mu2f(f)) / (e1f(f) - j * e2f(f)))) * (cmath.tanh(j * (2 * cmath.pi * (f * 10**9) * (d * 0.001) / 299792458) * cmath.sqrt( (mu1f(f) - j * mu2f(f)) * (e1f(f) - j * e2f(f)))))) + 1))))) # return inputted data for documentation and return # the real portion of y to drop complex portion # of form j*0 return y.real, f, d
def tanh(x): """ Uncertain number hyperbolic tangent function """ try: return x._tanh() except AttributeError: if isinstance(x, numbers.Real): return math.tanh(x) elif isinstance(x, numbers.Complex): return cmath.tanh(x) else: raise TypeError("illegal argument: {!r}".format(x))
def coth(z): """ An AlComplex compatible hyperbolic cotangent function. Parameters ---------- z : Python numeric type or AlComplex Returns ------- AlComplex """ z = real_to_complex(z) return AlComplex.from_python_complex(cm.tanh(z.to_python_complex())**-1)
def dichroic_plate(radius, spacing, thickness): # For radius>0.28*spacing and spacing<0.57 * wavelength A = 0.5 * _np.sqrt(3.0) # hexagonal guide array fc1 = 1e-9*1.841*cc/(_np.pi*2.0*radius) # [GHz], designed lower cut-off frequency fc2 = 1e-9*cc/(spacing*A) # [GHz], diffraction limited upper cut-off frequency # wlco = cc/(1e9*fc1)/_np.sqrt(eps3) J1prime = _scipy.special.jvp(v=1, z=4.0*_np.pi*radius/(_np.sqrt(3)*spacing), n=1) A = 12.0 * _np.sqrt(_np.asarray(4.0/3.0 * (wavelength/spacing)**2.0 - 1.0, dtype=complex)) \ * (J1prime/(1.0-(4*_np.pi*radius/(1.841*_np.sqrt(3.0)*spacing))**2.0))**2.0 A -= 12.0/_np.sqrt(_np.asarray(4.0/3.0 * (wavelength/spacing)**2.0 - 1.0, dtype=complex)) \ * (J1prime/(4.0*_np.pi*radius/(_np.sqrt(3.0)*spacing)))**2.0 B = 0.33*(spacing/radius)**2.0 * _np.sqrt(_np.asarray((0.293*wavelength/radius)**2.0 - 1.0, dtype=complex) ) beta = (2.0*_np.pi/wavelength)*_np.sqrt(_np.asarray((0.293*wavelength/radius)**2.0 - 1.0, dtype=complex)) R2 = _np.zeros( (len(freq),), dtype=complex) T2 = _np.zeros_like(R2) for ii in range(len(freq)): R2[ii] = 1.0 / (1.0 - 1j*(A[ii]+B[ii]*cmath.tanh(beta[ii]*thickness))) + 1.0/(1.0-1j*(A[ii]+B[ii]*coth(beta[ii]*thickness))) - 1.0 T2[ii] = 1.0 / (1.0 - 1j*(A[ii]+B[ii]*cmath.tanh(beta[ii]*thickness))) - 1.0/(1.0-1j*(A[ii]+B[ii]*coth(beta[ii]*thickness))) # print(_np.abs(R2[ii]), _np.abs(1-T2[ii])) # end for # Porosity por = _np.pi*(2.0*radius)**2.0 / (2.0*_np.sqrt(3)*spacing**2.0) T2 = _np.abs(T2) R2 = _np.abs(R2) print("Dichroic plate characteristics: ") print("Hexagonal hole pattern: diameter=%2.2f mm, spacing=%2.2f mm, thickness=%2.2f mm"%(1e3*2.0*radius, 1e3*spacing, 1e3*thickness)) print("filter cut-offs: %3.1f<f<%3.1f GHz"%(fc1, fc2)) # return T2perp, T2parr, por, fc1, fc2 return T2, R2, por, fc1, fc2
def tanh(x): """ Return the hyperbolic tangent of x. """ if isinstance(x,ADF): ad_funcs = list(map(to_auto_diff,[x])) x = ad_funcs[0].x ######################################## # Nominal value of the constructed ADF: f = tanh(x) ######################################## variables = ad_funcs[0]._get_variables(ad_funcs) if not variables or isinstance(f, bool): return f ######################################## # Calculation of the derivatives with respect to the arguments # of f (ad_funcs): lc_wrt_args = [1./(cosh(x))**2] qc_wrt_args = [-2*sinh(x)/(cosh(x))**3] cp_wrt_args = 0.0 ######################################## # Calculation of the derivative of f with respect to all the # variables (Variable) involved. lc_wrt_vars,qc_wrt_vars,cp_wrt_vars = _apply_chain_rule( ad_funcs,variables,lc_wrt_args,qc_wrt_args, cp_wrt_args) # The function now returns an ADF object: return ADF(f, lc_wrt_vars, qc_wrt_vars, cp_wrt_vars) else: # try: # pythonic: fails gracefully when x is not an array-like object # return [tanh(xi) for xi in x] # except TypeError: if x.imag: return cmath.tanh(x) else: return math.tanh(x.real)
def tanh(x): """ Return the hyperbolic tangent of x. """ if isinstance(x, ADF): ad_funcs = list(map(to_auto_diff, [x])) x = ad_funcs[0].x ######################################## # Nominal value of the constructed ADF: f = tanh(x) ######################################## variables = ad_funcs[0]._get_variables(ad_funcs) if not variables or isinstance(f, bool): return f ######################################## # Calculation of the derivatives with respect to the arguments # of f (ad_funcs): lc_wrt_args = [1. / (cosh(x))**2] qc_wrt_args = [-2 * sinh(x) / (cosh(x))**3] cp_wrt_args = 0.0 ######################################## # Calculation of the derivative of f with respect to all the # variables (Variable) involved. lc_wrt_vars, qc_wrt_vars, cp_wrt_vars = _apply_chain_rule( ad_funcs, variables, lc_wrt_args, qc_wrt_args, cp_wrt_args) # The function now returns an ADF object: return ADF(f, lc_wrt_vars, qc_wrt_vars, cp_wrt_vars) else: # try: # pythonic: fails gracefully when x is not an array-like object # return [tanh(xi) for xi in x] # except TypeError: if x.imag: return cmath.tanh(x) else: return math.tanh(x.real)
def W(p, f): """ defines a blocked boundary Finite-length Warburg Element Notes --------- .. math:: Z = \\frac{R}{\\sqrt{ T \\times j 2 \\pi f}} \\coth{\\sqrt{T \\times j 2 \\pi f }} where :math:`R` = p[0] (Ohms) and :math:`T` = p[1] (sec) = :math:`\\frac{L^2}{D}` """ omega = 2 * np.pi * np.array(f) Zw = np.vectorize(lambda y: p[0] / (np.sqrt(p[1] * 1j * y) * cmath.tanh( np.sqrt(p[1] * 1j * y)))) return Zw(omega)
def __coeff(self, f, dl, rl): """ DESCRIPTION: ----------- Computes the transmission and reflection coefficients. Based on Wannamaker's subroutine 'COAMP' in 'MT2D' ARGUMENTS: ----------- f :: sounding frequency. dl :: layer thicknesses. rl :: layer resistivities. """ # --- # Initialise (return) lists for coefficients. # --- # Number of layers. nl = len(rl) # Transmission and Reflection coefficients "an" and "rn" an = [ complex(0.0,00) ]*(nl) rn = [ complex(0.0,00) ]*(nl) # --- # Constant values. # --- pi = cmath.pi # Ratio of circle circumference to it's diameter. ra = 1.0e+14 # Resistivity of air. mu = 4*pi*1e-7 # Free space permeability. w = 2*pi*f # Angular frequency. wm = w*mu # Shortcut of product. # --- # Calculate intrinsic wave numbers <quasi-static>. # --- # Wave number of air: k0 = cmath.sqrt( -1j*wm/ra ) # Cycle layers and compute wave numbers of other layers: k = [None]*nl for i in range(nl): k[i] = cmath.sqrt( -1j*wm/rl[i] ) # --- # Reflection & transmission coefficients for half-space. # --- # Half-space case: if nl == 1: an[0] = 2*k0/(k[0] + k0) # = 1+Ro rn[0] = (k0 - k[0])/(k0 + k[0]) # All done, return the coefficients. return an, rn # --- # Prepare calculations for layers. # --- # Initialise lists for computed values with complex zeros. arg = [ complex(0.0,00) ]*(nl-1) exp = [ complex(0.0,00) ]*(nl-1) ex2 = [ complex(0.0,00) ]*(nl-1) tnh = [ complex(0.0,00) ]*(nl-1) # Setup arguments for the exponential for each layer.. # .. and compute the tanh function and also exp(-2kh). for j in range(nl-1): arg[j] = 1j*k[j]*dl[j] tnh[j]= cmath.tanh(arg[j]) # Save also exponentials for coefficient calculations later: exp[j] = cmath.exp( -arg[j] ) ex2[j] = exp[j]*exp[j] # --- # Reflection & transmission coefficients for layers. # --- #<Note>: Following section is based on the formulae by Wannamaker's code. # Initialise recursion with intrinsic impedance of basement. zn = wm/k[nl-1] # Compute the reflection coefficients for all sub-surface layers.. # ..start the loop at the basement and cycle up to the first layer: for j in range(nl-1,0,-1): # Wave impedance of next layer-up: zu = wm/k[j-1] # Ratio of layer impedances of current-layer and layer-up:: rn[j] = (zn - zu)/(zn + zu) # New apparent impedance for up-layer via Wait's formula: zn = zu*(zn + zu*tnh[j-1])/(zu + zn*tnh[j-1]) # <Note>: "zn" is the surface impedance when finishing the loop. # For the first sub-surface layer, we also .. # ..have to mind the air-layer at index '0': zu = wm/k0 ; rn[0] = (zn - zu)/(zn + zu) # Transmission coefficient of first layer takes into account air-layer: an[0] = (1+rn[0]) / (1+rn[1]*ex2[0]) # exp[0]* #<Note>: Wannamaker does not multiply with exp! # And now compute the transmission coefficients for rest of the layers: if (nl-1) > 1: for n in range(1,nl-1): #<Note>: Wannamaker uses num: ~ exp[n-1]! num = (1+rn[n] )*exp[n-1] den = (1+rn[n+1]*ex2[n]) an[n] = an[n-1]*num/den # And mind the basement as well (numerator is 1): an[nl-1] = an[nl-2]*exp[nl-2]*(1+rn[nl-1]) # Return the coefficients. return an, rn
'tan': lambda x: cmath.tan(x), 'csc': lambda x: 1/cmath.sin(x), 'sec': lambda x: 1/cmath.cos(x), 'cot': lambda x: 1/cmath.tan(x), 'ln': lambda x: cmath.log(x), 'log': lambda x: cmath.log(x)/cmath.log(10), 'fact': lambda x: factorial(int(x)), 'asin': lambda x: cmath.asin(x), 'acos': lambda x: cmath.acos(x), 'atan': lambda x: cmath.atan(x), 'acsc': lambda x: cmath.asin(1/x), 'asec': lambda x: cmath.acos(1/x), 'acot': lambda x: cmath.atan(1/x), 'sinh': lambda x: cmath.sinh(x), 'cosh': lambda x: cmath.cosh(x), 'tanh': lambda x: cmath.tanh(x), 'csch': lambda x: 1/cmath.sinh(x), 'sech': lambda x: 1/cmath.cosh(x), 'coth': lambda x: 1/cmath.tanh(x), 'asinh': lambda x: cmath.asinh(x), 'acosh': lambda x: cmath.acosh(x), 'atanh': lambda x: cmath.atanh(x), 'acsch': lambda x: cmath.asinh(1/x), 'asech': lambda x: cmath.acosh(1/x), 'acoth': lambda x: cmath.atanh(1/x) } def replace_variables(phrase, replacement, var = 'x'): """Replaces all instances of a named variable in a phrase with a replacement, 'x' by default.""" i = 0
def __new__(cls, argument): if isinstance(argument, (RealValue, Zero)): return FloatValue(math.tanh(float(argument))) if isinstance(argument, (ComplexValue)): return ComplexValue(cmath.tanh(complex(argument))) return MathFunction.__new__(cls)
def LaplaceHead(self, P): '''Laplace transform of dimensionless head (hD_bar) as given in its full form in equation (11) of Zhou et al 2009 P Laplace variable''' #f_bar as used in Zhou et al 2009 is the combination of the upper #and lower contributions #aquifer only, no leaky layer f_bar = 0.0 #aquifer + 1 leaky layer if len(self.S) > 1: #from equation (6d) of Zhou et al 2009 #mt is computed in the function FindZhouVariables fullmt = self.mt * cmath.sqrt(P) #the expression for f_bar in equation (8) of Zhou et al 2009 #is simplified if leaky layer storage is neglected, or #the storage factor is very low if self.sigmat <= 2e-10: #simplified f_bar = self.lambdat**2 else: #full expression if fullmt.real > 500.0: f_bar = self.lambdat**2 * fullmt else: #constant head leaky layer boundary condition if self.LLbc == 'constant': f_bar = self.lambdat**2 * fullmt \ / cmath.tanh(fullmt) #no-flow leaky layer boundary condition else: f_bar = self.lambdat**2 * fullmt \ * cmath.tanh(fullmt) #aquifer + 2 leaky layers if len(self.S) > 2: #from equation (6d) of Zhou et al 2009 #mb is computed in the function SetLBLVariables fullmb = self.mb * cmath.sqrt(P) #the expression for f_bar in equation (8) of Zhou et al 2009 #is simplified if leaky layer storage is neglected, or #the storage factor is very low if self.sigmab <= 2e-10: #simplified f_bar += self.lambdab**2 else: #full expression if fullmb.real > 500.0: f_bar += self.lambdab**2 * fullmb else: #constant head leaky layer boundary condition if self.LLbc == 'constant': f_bar += self.lambdab**2 * fullmb \ / cmath.tanh(fullmb) #no-flow leaky layer boundary condition else: f_bar = self.lambdab**2 * fullmb \ * cmath.tanh(fullmb) #from equation (10) of Zhou et al 2009 x = cmath.sqrt(P + f_bar) #bounded aquifer if self.rb > 0: #to avoid numerical problems at early times temp = self.rDb * x #infinitesimal well radius if self.rw == -1: if temp.real > 500.0: hD_bar = 2.0 / P \ * sci.kv(0.0, self.rD * x) else: hD_bar = 2.0 / P \ * (sci.kv(1.0, self.rDb * x) \ * sci.iv(0.0, self.rD * x) \ + sci.iv(1.0, self.rDb * x) \ * sci.kv(0.0, self.rD * x)) \ / sci.iv(1.0, self.rDb * x) #finite well radius else: if temp.real > 500.0: #to avoid numerical problems for VERY early times #and close to the injection well if sci.kv(0.0, x * self.rD) == 0j \ and sci.kv(1.0, self.rDw * x) == 0j: hD_bar = 2.0 / (self.rDw * x * P) else: hD_bar = 2.0 * sci.kv(0.0, x * self.rD) \ / (self.rDw * x * P \ * sci.kv(1.0, self.rDw * x)) else: hD_bar = 2.0 / (self.rDw * P * x) * \ (sci.kv(1.0, self.rDb * x) * sci.iv(0.0, self.rD * x) \ + sci.iv(1.0, self.rDb * x) * sci.kv(0.0, self.rD * x)) \ / (sci.iv(1.0, self.rDb * x) * sci.kv(1.0, self.rDw * x) \ - sci.kv(1.0, self.rDb * x) * sci.iv(1.0, self.rDw * x)) #infinite aquifer else: #infinitesimal well radius if self.rw == -1: hD_bar = 2.0 / P * sci.kv(1.0, self.rDb * x) #finite well radius else: #to avoid numerical problems for VERY early times #and close to the injection well if sci.kv(0.0, x * self.rD) == 0j \ and sci.kv(1.0, self.rDw * x) == 0j: hD_bar = 2.0 / (self.rDw * x * P) else: hD_bar = 2.0 / (self.rDw * P * x) \ * sci.kv(0.0, self.rD * x) \ / sci.kv(1.0, self.rDw * x) return hD_bar
def testTanhSign(self): for z in complex_zeros: self.assertComplexIdentical(cmath.tanh(z), z)
def test_tanh(self): self.assertAlmostEqual(complex(1.00071, 0.00490826), cmath.tanh(complex(3, 4)))
im2 = -sin(2*beta)/(cosh(2*beta) - cos(2*alpha)) print 're2 = ', re2, '\nim2 = ', im2 print 'x = ', x, ':' ax = alpha*x bx = beta*x mcos = sin(ax)*sinh(bx) - cos(ax)*sinh(bx)*im - sin(ax)*cosh(bx)*re msin = cos(ax)*cosh(bx) - cos(ax)*sinh(bx)*re + sin(ax)*cosh(bx)*im mcos *=sqrt(2) msin*=sqrt(2) print 'mcos = ', mcos, '\nmsin = ', msin x = 1 print 'x = ', x, ':' ax = alpha*x bx = beta*x mcos = sin(ax)*sinh(bx) - cos(ax)*sinh(bx)*im - sin(ax)*cosh(bx)*re msin = cos(ax)*cosh(bx) - cos(ax)*sinh(bx)*re + sin(ax)*cosh(bx)*im mcos *=sqrt(2) msin*=sqrt(2) print 'mcos = ', mcos, '\nmsin = ', msin gamma = beta+1j*alpha zvi = 1/cmath.tanh(gamma) print 'zvi', zvi
def D(alpha, h): ''' alpha = alpha() h = height of conductor ''' return 2.0*alpha*h*cmath.tanh(alpha*h/2.0)
# Hyperbolic functions - real version x = 0.5 assert abs(cosh(x) - math.cosh(x)) < 1e-14 assert abs(sinh(x) - math.sinh(x)) < 1e-14 assert abs(tanh(x) - math.tanh(x)) < 1e-14 #------------------------------------------------------------------------------ # Hyperbolic functions - complex version x = 0.5j assert abs(cosh(x) - cmath.cosh(x)) < 1e-14 assert abs(sinh(x) - cmath.sinh(x)) < 1e-14 assert abs(tanh(x) - cmath.tanh(x)) < 1e-14 assert abs(acosh(x) - cmath.acosh(x)) < 1e-14 assert abs(asinh(x) - cmath.asinh(x)) < 1e-14 assert abs(atanh(x) - cmath.atanh(x)) < 1e-14 #------------------------------------------------------------------------------ # Rounding operations. assert type(round(0.5)) is mpf assert type(round(mpq(1,2))) is mpf assert type(floor(0.5)) is mpf assert type(ceil(0.5)) is mpf assert round(0.5) == 1 assert round(-0.5) == -1
def IBLCalc(epsilon, M, corPar, MS, MODB, stratPar_back, EkmanDepth_back, frVelCpx_back, tempScale_back, roughLength_m_back, roughLength_h_back, tempTop, gam, tempSurf_back, geostrWindCpx, d, tempSurf, roughLength_h, roughLength_m, stratPar, frVelCpx, tempScale): CHARNOCKCONST = 0.018 GRAVITYACC = 9.8 VONKARMANCONST = 0.41 BETA = GRAVITYACC / 300 VA = 14e-6 SBLHeight_back = epsilon * EkmanDepth_back K_back = EkmanDepth_back ** 2 * corPar / 2 K = K_back geostrWind = abs(geostrWindCpx) angle = cmath.phase(geostrWindCpx) d -= epsilon dm = M - epsilon tmpUWind = geostrWind * math.cos(angle) # iteration for the drag coefficient it = 0 mistake = 1 tmpFrVelCpx = frVelCpx tmpTempScale = tempScale gama = max(0, gam) alpha = 1 epst = 0 lambInv_back = 1 / lambdaCalc(epsilon, stratPar_back) while mistake > 0.0001: it += 1 tmpFrVelCpx = 0.3 * frVelCpx + 0.7 * tmpFrVelCpx tmpFrVel = abs(tmpFrVelCpx) tmpTempScale = 0.3 * tempScale + 0.7 * tmpTempScale heatFlux = - tmpFrVel * tmpTempScale stratPar = VONKARMANCONST ** 2 * BETA * tmpTempScale / (corPar * tmpFrVel) roughLength_m = roughLength_m * MS + \ (CHARNOCKCONST * tmpFrVel ** 2 / GRAVITYACC + 0.14 * VA / tmpFrVel) * (1 - MS) lambInv = 1 / lambdaCalc(epsilon, stratPar) profileFunc_m = profileFunc_momentum_Calc(lambInv, epsilon, stratPar) profileFunc_h = profileFunc_heat_Calc(lambInv, epsilon, stratPar) EkmanDepth = VONKARMANCONST * tmpFrVel / (corPar * lambInv) SBLHeight = epsilon * EkmanDepth K = EkmanDepth ** 2 * corPar / 2 delta = EkmanDepth * (d + epsilon) if delta <= SBLHeight_back: tmpStratPar_back = stratPar_back * delta / SBLHeight_back profileFunc_m_back = profileFunc_momentum_Calc(lambInv_back, epsilon, tmpStratPar_back) profileFunc_h_back = profileFunc_heat_Calc(lambInv_back, epsilon, tmpStratPar_back) windCpx_back = frVelCpx_back / VONKARMANCONST * (math.log(delta / roughLength_m_back) - profileFunc_m_back) temp = tempSurf_back + tempScale_back / VONKARMANCONST *\ (math.log(delta / roughLength_h_back) - profileFunc_h_back) else: ksi = (delta - SBLHeight_back) / (EkmanDepth_back * dm) tmpKsi = ksi ksi = min(1, ksi) Coeff = (1 -1j) * cmath.sinh((1 + 1j) * dm * (1 - ksi)) / cmath.cosh((1 + 1j) * dm) windCpx_back = geostrWindCpx - lambInv_back * frVelCpx_back / VONKARMANCONST * Coeff temp = tempTop - 2 * lambInv_back * tempScale_back / VONKARMANCONST * dm * (1 - tmpKsi) if gam <= 0: alg = 1 epst = 0 else: alg = (abs(heatFlux) + abs(gama * K_back)) / (abs(heatFlux) + abs(gama * K)) alg = min(1, alg) epst = max(0, 1 / 4 * heatFlux / (K * gama * alg)) temp -= epst * gama * delta alpha = alg * (1 - (delta / (M * EkmanDepth)) ** 4) alpha = max(0, alpha) Coeff = cmath.tanh((1 + 1j) * d) A = lambInv * Coeff B = - A + profileFunc_m - math.log(VONKARMANCONST * epsilon / lambInv) C = -2 * lambInv * d + profileFunc_h - math.log(VONKARMANCONST * epsilon / lambInv) F = 1j * VONKARMANCONST / tmpFrVelCpx * BETA / (corPar * tmpUWind) * d ** 2 / (d ** 2 - 1j * alpha) F *= heatFlux F *= MODB frVelCpx = VONKARMANCONST * geostrWindCpx / (math.log(tmpFrVel / (corPar * roughLength_m)) - B - 1j * A + F) frVelCpx *= (1 + (windCpx_back / geostrWindCpx -1) / cmath.cosh((1 + 1j) * d)) tempScale = VONKARMANCONST * (temp - tempSurf) / (math.log(tmpFrVel / (corPar * roughLength_h)) - C) mistake = abs(tmpFrVelCpx - frVelCpx) / abs(tmpFrVelCpx) if it > 100: print 'error in IBLCalc' break RES = [stratPar, EkmanDepth, frVelCpx, tempScale, temp, roughLength_m, windCpx_back, alpha, epst] return RES
def GeostrophicWindCalc(windCpx, tempSurf, tempSurf2, gradient, lat, M=2.05): """ calculates geostrophic wind speed and direction input: windCpx - wind at 10 meters (complex), tempAtm - temperature at top of PBL, tempSurf - surface temperature, lat - latitude output: geostrWindCpx - geostrophic wind, complex number """ GRAVITYACC = 9.8 VONKARMANCONST = 0.41 BETA = GRAVITYACC / 300. OMEGA = 7.3e-5 epsilon = 0.15 # M = 2.05 CHARNOCKCONST = 0.018 corPar = 2. * math.sin(math.radians(lat)) * OMEGA roughLength_h = 1e-5 mistake = 1 frVelCpx = math.sqrt(0.5e-3) * windCpx tmpfrVelCpx = frVelCpx while mistake > 0.001: roughLength_m = CHARNOCKCONST * abs(frVelCpx) ** 2. / GRAVITYACC frVelCpx = VONKARMANCONST * windCpx / (math.log(10. / roughLength_m)) mistake = abs(tmpfrVelCpx - frVelCpx) / abs(tmpfrVelCpx) tmpfrVelCpx = frVelCpx it = 0 stratPar = VONKARMANCONST ** 2. * BETA * ( tempSurf2 + gradient * 100 - tempSurf) / (corPar * 1.5 * abs(windCpx)) if abs(stratPar) > 10e-15: tmpD = 100 mistake = 1 while mistake > 0.01: it += 1 lambInv = 1. / lambdaCalc(epsilon, stratPar) C = -2. * lambInv * (M - epsilon) +\ profileFunc_heat_Calc(lambInv, epsilon, stratPar) - \ math.log(VONKARMANCONST * epsilon / lambInv) EkmanDepth = tmpD tempScale = VONKARMANCONST * \ (tempSurf2 - tempSurf + gradient * M * EkmanDepth) /\ (math.log(abs(frVelCpx) / (corPar * roughLength_h)) - C) stratPar = VONKARMANCONST ** 2 * BETA * tempScale / \ (corPar * abs(frVelCpx)) EkmanDepth = VONKARMANCONST * abs(frVelCpx) / (corPar * lambInv) mistake = abs(tmpD - EkmanDepth) / abs(tmpD) tmpD = 0.3 * EkmanDepth + 0.7 * tmpD if it > 100: break else: stratPar = 0 lambInv = 1. / lambdaCalc(epsilon, stratPar) A = lambInv * cmath.tanh((1 + 1j) * (M - epsilon)) B = - A + profileFunc_momentum_Calc(lambInv, epsilon, stratPar) - math.log( VONKARMANCONST * epsilon / lambInv) geostrWindCpx = frVelCpx / VONKARMANCONST * \ (math.log( abs(frVelCpx) / (corPar * roughLength_m)) - B - 1j * A) return geostrWindCpx, stratPar
def rpn_calc(input, angle_mode = 0): global stack single_arg_funcs = ['exp','sqrt','sin','asin','cos','acos','tan','atan', 'sinh','asinh','cosh','acosh','tanh', 'atanh','!', 'polar'] num, arg, option = parse(input) #print(num, arg, option) #print('\n') if arg == None and (num != None or num != 'Error'): config.stack.append(num) history.append('Entered number: ' + str(num) ) return config.stack # Simple arithmatic----------------------------------------------------------------------- if option == None and num != None: if arg not in single_arg_funcs: last = config.stack.pop() if arg == '+': try: result = Decimal(last) + Decimal(num) hist = str(last) + '+' + str(num) + '=' + str(result) except TypeError: result = last + num hist = str(last) + '+' + str(num) + '=' + str(result) if arg == '-': try: result = Decimal(last) - Decimal(num) hist = str(last) + '-' + str(num) + '=' + str(result) except TypeError: result = last - num hist = str(last) + '-' + str(num) + '=' + str(result) if arg == '*': try: result = Decimal(last) * Decimal(num) hist = str(last) + '*' + str(num) + '=' + str(result) except TypeError: result = last * num hist = str(last) + '*' + str(num) + '=' + str(result) if arg == '/': try: result = Decimal(last) / Decimal(num) hist = str(last) + '/' + str(num) + '=' + str(result) except TypeError: result = last / num hist = str(last) + '/' + str(num) + '=' + str(result) if arg == '**': try: result = pow(Decimal(last), Decimal(num) ) hist = str(last) + '**' + str(num) + '=' + str(result) except TypeError: result = last ** num hist = str(last) + '**' + str(num) + '=' + str(result) if arg == 'rt': try: result = root(Decimal(last), Decimal(num) ) hist = str(last) + 'raised to 1 over ' + str(num) + '=' + str(result) except TypeError: result = root(last + num) hist = str(last) + 'raised to 1 over ' + str(num) + '=' + str(result) if arg == '%': try: result = Decimal(last) % Decimal(num) hist = str(last) + '%' + str(num) + '=' + str(result) except TypeError: result = last % num hist = str(last) + '%' + str(num) + '=' + str(result) if arg == '!': try: result = Decimal(math.factorial(num)) hist = str(num) + '!' + '=' + str(result) except TypeError: result = math.factorial(num) hist = str(num) + '!' + '=' + str(result) if arg == 'exp': try: result = math.exp(Decimal(num)) hist = str(num) + 'exp' + '=' + str(result) except ValueError: result = cmath.exp(Decimal(num)) hist = str(num) + 'exp' + '=' + str(result) except TypeError: result = cmath.exp(num) hist = str(num) + 'exp' + '=' + str(result) if arg == 'sqrt': try: result = math.sqrt(Decimal(num)) hist = str(num) + 'sqrt' + '=' + str(result) except ValueError: result = cmath.sqrt(Decimal(num)) hist = str(num) + 'sqrt' + '=' + str(result) except TypeError: result = cmath.sqrt(num) hist = str(num) + 'sqrt' + '=' + str(result) if arg == 'log': try: result = math.log10(Decimal(num)) hist = str(num) + 'log10' + '=' + str(result) except ValueError: result = cmath.log10(Decimal(num)) hist = str(num) + 'log10' + '=' + str(result) except TypeError: result = cmath.log10(num) hist = str(num) + 'log10' + '=' + str(result) #================================= if arg == 'ln': try: result = math.log(Decimal(num)) hist = str(num) + 'ln' + '=' + str(result) except ValueError: result = cmath.log(Decimal(num)) hist = str(num) + 'ln' + '=' + str(result) except TypeError: result = cmath.log(num) hist = str(num) + 'ln' + '=' + str(result) #--------TRIG-------------------------------- if arg == 'sin': if angle_mode == 1: try: result = math.sin(Decimal(num)) hist = 'sin' + str(num) + '=' + str(result) except TypeError: result = cmath.sin(num) hist = 'sin' + str(num) + '=' + str(result) elif angle_mode == 0: try: result = math.sin(math.radians(Decimal(num))) hist = 'sin' + str(num) + '=' + str(result) except TypeError: result = cmath.sin(num) hist = 'sin' + str(num) + '=' + str(result) if arg == 'cos': if angle_mode == 1: try: result = math.cos(Decimal(num)) hist = 'cos' + str(num) + '=' + str(result) except TypeError: result = cmath.cos(num) hist = 'cos' + str(num) + '=' + str(result) elif angle_mode == 0: try: result = math.cos(math.radians(Decimal(num))) hist = 'cos' + str(num) + '=' + str(result) except TypeError: result = cmath.cos(num) hist = 'cos' + str(num) + '=' + str(result) if arg == 'tan': if angle_mode == 1: try: result = math.tan(Decimal(num)) hist = 'tan' + str(num) + '=' + str(result) except TypeError: result = cmath.tan(num) hist = 'tan' + str(num) + '=' + str(result) elif angle_mode == 0: try: result = math.tan(math.radians(Decimal(num))) hist = 'tan' + str(num) + '=' + str(result) except TypeError: result = cmath.tan(num) hist = 'tan' + str(num) + '=' + str(result) if arg == 'asin': if angle_mode == 1: try: result = math.asin(Decimal(num)) hist = 'asin' + str(num) + '=' + str(result) except TypeError: result = cmath.asin(num) hist = 'asin' + str(num) + '=' + str(result) elif angle_mode == 0: try: result = math.asin(math.radians(Decimal(num))) hist = 'asin' + str(num) + '=' + str(result) except TypeError: result = cmath.asin(num) hist = 'asin' + str(num) + '=' + str(result) if arg == 'acos': if angle_mode == 1: try: result = math.acos(Decimal(num)) hist = 'acos' + str(num) + '=' + str(result) except TypeError: result = cmath.acos(num) hist = 'acos' + str(num) + '=' + str(result) elif angle_mode == 0: try: result = math.acos(math.radians(Decimal(num))) hist = 'acos' + str(num) + '=' + str(result) except TypeError: result = cmath.acos(num) hist = 'acos' + str(num) + '=' + str(result) if arg == 'atan': if angle_mode == 1: try: result = math.atan(Decimal(num)) hist = 'atan' + str(num) + '=' + str(result) except TypeError: result = cmath.atan(num) hist = 'atan' + str(num) + '=' + str(result) elif angle_mode == 0: try: result = math.atan(math.radians(Decimal(num))) hist = 'atan' + str(num) + '=' + str(result) except TypeError: result = cmath.atan(num) hist = 'atan' + str(num) + '=' + str(result) if arg == 'sinh': try: result = math.sinh(Decimal(num)) hist = 'sinh' + str(num) + '=' + str(result) except TypeError: result = cmath.sinh(num) hist = 'sinh' + str(num) + '=' + str(result) if arg == 'cosh': try: result = math.cosh(Decimal(num)) hist = 'cosh' + str(num) + '=' + str(result) except TypeError: result = cmath.cosh(num) hist = 'cosh' + str(num) + '=' + str(result) if arg == 'tanh': try: result = math.tanh(Decimal(num)) hist = 'tanh' + str(num) + '=' + str(result) except TypeError: result = cmath.tanh(num) hist = 'tanh' + str(num) + '=' + str(result) if arg == 'asinh': try: result = math.asinh(Decimal(num)) hist = 'asinh' + str(num) + '=' + str(result) except TypeError: result = cmath.asinh(num) hist = 'asinh' + str(num) + '=' + str(result) if arg == 'acosh': try: result = math.acosh(Decimal(num)) hist = 'acosh' + str(num) + '=' + str(result) except TypeError: result = cmath.acosh(num) hist = 'acosh' + str(num) + '=' + str(result) if arg == 'atanh': try: result = math.atanh(Decimal(num)) hist = 'atanh' + str(num) + '=' + str(result) except TypeError: result = cmath.atanh(num) hist = 'atanh' + str(num) + '=' + str(result) if arg == 'rect': #continue here.... try: result = rect(last, num) hist = 'Convert ' + str(last) + ',' + str(num) + ' to rectangular coords.' except TypeError: result = 'Error' hist = 'Error in attempted conversion to rectangular coords. No result.' if arg == 'polar': try: result = polar(num) hist = 'Convert ' + str(num) + ' to polar coords.' except TypeError: result = 'Error' hist = 'Error in attempted conversion to polar coords. No result.' config.stack.append(result) history.append(hist) return config.stack #======================================================================================================================= #----Only argument passed----------------------------------------------------------------------------------------------- #======================================================================================================================= elif option == None and num == None: last = config.stack.pop() if arg not in single_arg_funcs: try: n_minus1 = config.stack.pop() except IndexError: try: config.stack.append(Decimal(last)) except TypeError: config.stack.append(last) except TypeError: config.stack.append(last) except Exception as e: return 'Error' if arg == '+': try: result = Decimal(n_minus1) + Decimal(last) hist = str(n_minus1) + '+' + str(last) + '=' + str(result) except TypeError: result = n_minus1 + last hist = str(n_minus1) + '+' + str(last) + '=' + str(result) if arg == '-': try: result = Decimal(n_minus1) - Decimal(last) hist = str(n_minus1) + '-' + str(last) + '=' + str(result) except TypeError: result = n_minus1 - last hist = str(n_minus1) + '-' + str(last) + '=' + str(result) if arg == '*': try: result = Decimal(n_minus1) * Decimal(last) hist = str(n_minus1) + '*' + str(last) + '=' + str(result) except TypeError: result = n_minus1 * last hist = str(n_minus1) + '*' + str(last) + '=' + str(result) if arg == '/': try: result = Decimal(n_minus1) / Decimal(last) hist = str(n_minus1) + '/' + str(last) + '=' + str(result) except TypeError: result = n_minus1 / last hist = str(n_minus1) + '/' + str(last) + '=' + str(result) if arg == '!': try: result = Decimal(math.factorial(last)) hist = str(last) + '!' '=' + str(result) except TypeError: result = math.factorial(last) hist = str(last) + '!' '=' + str(result) except OverflowError: config.stack.append(last) hist = str('Factorial overflow error, no result.') return 'Error' if arg == '**': try: result = pow(Decimal(last), Decimal(last)) hist = str(n_minus1) + '**' + str(last) + '=' + str(result) except TypeError: result = last ** last hist = str(n_minus1) + '**' + str(last) + '=' + str(result) if arg == 'log': try: result = math.log10(Decimal(last)) hist = str(last) +'log10' + '=' + str(result) except ValueError: result = cmath.log10(Decimal(last)) hist = str(last) +'log10' + '=' + str(result) except TypeError: result = cmath.log10(last) hist = str(last) +'log10' + '=' + str(result) if arg == 'ln': try: result = math.log(Decimal(last)) hist = str(last) +'ln' + '=' + str(result) except ValueError: result = cmath.log(Decimal(last)) hist = str(last) +'ln' + '=' + str(result) except TypeError: result = cmath.log(last) hist = str(last) +'ln' + '=' + str(result) if arg == 'rt': try: result = root(Decimal(last), Decimal(n_minus1)) hist = str(n_minus1) + 'root' + str(last) + '=' + str(result) except TypeError: result = root(last), (n_minus1) hist = str(n_minus1) + 'root' + str(last) + '=' + str(result) if arg == 'exp': try: result = math.exp(Decimal(last)) hist = str(last) +'exp' + '=' + str(result) except TypeError: result = cmath.exp(last) hist = str(last) +'exp' + '=' + str(result) if arg == 'sqrt': try: result = math.sqrt(Decimal(last)) hist = 'Square root of ' + str(last) + '=' + str(result) except ValueError: result = cmath.sqrt(Decimal(last)) hist = 'Square root of ' + str(last) + '=' + str(result) except TypeError: result = cmath.sqrt(last) hist = 'Square root of ' + str(last) + '=' + str(result) #----------Trig---------------------------------------- #--------TRIG-------------------------------- if arg == 'sin': if angle_mode == 1: try: result = math.sin(Decimal(last)) hist = 'sin' + str(last) + '=' + str(result) except TypeError: result = cmath.sin(last) hist = 'sin' + str(last) + '=' + str(result) elif angle_mode == 0: try: result = math.sin(math.radians(Decimal(last))) hist = 'sin' + str(last) + '=' + str(result) except TypeError: result = cmath.sin(last) hist = 'sin' + str(last) + '=' + str(result) if arg == 'cos': if angle_mode == 1: try: result = math.cos(Decimal(last)) hist = 'cos' + str(last) + '=' + str(result) except TypeError: result = cmath.cos(last) hist = 'cos' + str(last) + '=' + str(result) elif angle_mode == 0: try: result = math.cos(math.radians(Decimal(last))) hist = 'cos' + str(last) + '=' + str(result) except TypeError: result = cmath.cos(last) hist = 'cos' + str(last) + '=' + str(result) if arg == 'tan': if angle_mode == 1: try: result = math.tan(Decimal(last)) hist = 'tan' + str(last) + '=' + str(result) except TypeError: result = cmath.tan(last) hist = 'tan' + str(last) + '=' + str(result) elif angle_mode == 0: try: result = math.tan(math.radians(Decimal(last))) hist = 'tan' + str(last) + '=' + str(result) except TypeError: result = cmath.tan(last) hist = 'tan' + str(last) + '=' + str(result) if arg == 'asin': if angle_mode == 1: try: result = math.asin(Decimal(last)) hist = 'asin' + str(last) + '=' + str(result) except TypeError: result = cmath.asin(last) hist = 'asin' + str(last) + '=' + str(result) elif angle_mode == 0: try: result = math.asin(math.radians(Decimal(last))) hist = 'asin' + str(last) + '=' + str(result) except TypeError: result = cmath.asin(last) hist = 'asin' + str(last) + '=' + str(result) if arg == 'acos': if angle_mode == 1: try: result = math.acos(Decimal(last)) hist = 'acos' + str(last) + '=' + str(result) except TypeError: result = cmath.acos(last) hist = 'acos' + str(last) + '=' + str(result) elif angle_mode == 0: try: result = math.acos(math.radians(Decimal(last))) hist = 'acos' + str(last) + '=' + str(result) except TypeError: result = cmath.acos(last) hist = 'acos' + str(last) + '=' + str(result) if arg == 'atan': if angle_mode == 1: try: result = math.atan(Decimal(last)) hist = 'atan' + str(last) + '=' + str(result) except TypeError: result = cmath.atan(last) hist = 'atan' + str(last) + '=' + str(result) elif angle_mode == 0: try: result = math.atan(math.radians(Decimal(last))) hist = 'atan' + str(last) + '=' + str(result) except TypeError: result = cmath.atan(last) hist = 'atan' + str(last) + '=' + str(result) if arg == 'sinh': try: result = math.sinh(Decimal(last)) hist = 'sinh' + str(last) + '=' + str(result) except TypeError: result = math.sinh(last) hist = 'sinh' + str(last) + '=' + str(result) if arg == 'cosh': try: result = math.cosh(Decimal(last)) hist = 'cosh' + str(last) + '=' + str(result) except TypeError: result = math.cosh(last) hist = 'cosh' + str(last) + '=' + str(result) if arg == 'tanh': try: result = math.tanh(Decimal(last)) hist = 'tanh' + str(last) + '=' + str(result) except TypeError: result = math.tanh(last) hist = 'tanh' + str(last) + '=' + str(result) if arg == 'asinh': try: result = math.asinh(Decimal(last)) hist = 'asinh' + str(last) + '=' + str(result) except TypeError: result = math.asinh(last) hist = 'asinh' + str(last) + '=' + str(result) if arg == 'acosh': try: result = math.acosh(Decimal(last)) hist = 'acosh' + str(last) + '=' + str(result) except TypeError: result = math.acosh(last) hist = 'acosh' + str(last) + '=' + str(result) if arg == 'atanh': try: result = math.atanh(Decimal(last)) hist = 'atanh' + str(last) + '=' + str(result) except TypeError: result = math.atanh(last) hist = 'atanh' + str(last) + '=' + str(result) if arg == 'rect': #continue here.... try: result = rect(n_minus1, last) hist = 'Convert ' + str(n_minus1) + ',' + str(last) + ' to rectangular coords.' except TypeError: result = 'Error' hist = 'Error in attempted conversion to rectangular coords. No result.' if arg == 'polar': try: result = polar(last) hist = 'Convert complex value ' + str(last) + ' to rectangular coords.' except TypeError: result = 'Error' hist = 'Error in attempted conversion to polar coords. No result.' config.stack.append(result) history.append(hist) return config.stack
print('arc cosine =', cmath.acos(c)) print('arc tangent =', cmath.atan(c)) print('sine =', cmath.sin(c)) print('cosine =', cmath.cos(c)) print('tangent =', cmath.tan(c)) # hyperbolic functions c = 2 + 2j print('inverse hyperbolic sine =', cmath.asinh(c)) print('inverse hyperbolic cosine =', cmath.acosh(c)) print('inverse hyperbolic tangent =', cmath.atanh(c)) print('hyperbolic sine =', cmath.sinh(c)) print('hyperbolic cosine =', cmath.cosh(c)) print('hyperbolic tangent =', cmath.tanh(c)) # classification functions print(cmath.isfinite(2 + 2j)) # True print(cmath.isfinite(cmath.inf + 2j)) # False print(cmath.isinf(2 + 2j)) # False print(cmath.isinf(cmath.inf + 2j)) # True print(cmath.isinf(cmath.nan + 2j)) # False print(cmath.isnan(2 + 2j)) # False print(cmath.isnan(cmath.inf + 2j)) # False print(cmath.isnan(cmath.nan + 2j)) # True print(cmath.isclose(2+2j, 2.01+1.9j, rel_tol=0.05)) # True
def _n_Zgdl(self, Omega, nJ, params): """Returns the dimensionless Warburg GDL impedance""" return params["Rm"]*cmath.tanh(params["mu"]*params["nl_d"]*cmath.sqrt(1j*Omega/params['nD_d']))/cmath.sqrt(1j*Omega*params['nD_d'])
def backgroundCalc(epsilon, M, corPar, MS, MODB, windCpx, tempAtm, tempSurf, roughLength_m, roughLength_h, refLevel): ''' calculate parameters of background atmosphere: friction velocity, temperature scale, Ekman depth, geostrophic wind and temperature in free atmosphere input: epsilon - main fitting parameter of the model, M - constant, corPar - Coriolis parameter, MS - "0" if background is land and "1" if sea, MODB - , windCpx - wind at reference level (complex), tempAtm - temperature of background atmosphere at reference level, tempSurf - background surface temperature, roughLength_m - roughness length for momentum for background surface, roughLength_h - roughness length for heat for background surface, refLevel - reference level, m output: stratPar - stratification parameter, mu, EkmanDepth , frVelCpx - friction velocity for background atmosphere< complex number, tempScale - temperature scale for background atmosphere, roughLength_m - roughness length for momentum for background surface, roughLength_heat - roughness length for heat for background surface, tempTop - temperature in free atmosphere, gam - , tempSurf - background surface temperature, geostrWindCpx - geostrophic wind, complex number ''' CHARNOCKCONST = 0.018 GRAVITYACC = 9.8 VONKARMANCONST = 0.41 BETA = GRAVITYACC / 300. VA = 14e-6 #Iteration for the drag coefficient it = 0 mistake = 1 DragCoeff = 0.5e-3 tmpFrVelCpx = math.sqrt(DragCoeff) * windCpx stratPar = VONKARMANCONST ** 2. * BETA * (tempAtm - tempSurf) / (corPar * abs(windCpx)) XX = [] YY = [] while mistake > 0.0001: it += 1 tmpFrVel = abs(tmpFrVelCpx) roughLength_m = roughLength_m * (1 - MS) + \ (CHARNOCKCONST * tmpFrVel ** 2. / GRAVITYACC + 0.14 * VA / tmpFrVel) * MS lambInv = 1. / lambdaCalc(epsilon, stratPar) EkmanDepth = VONKARMANCONST * tmpFrVel / (corPar * lambInv) SBLHeight = epsilon * EkmanDepth dH = refLevel / EkmanDepth dH1 = min(dH, M) if dH <= epsilon: stratPar1 = dH / epsilon * stratPar profileFunc_m = profileFunc_momentum_Calc(lambInv, epsilon, stratPar1) profileFunc_h = profileFunc_heat_Calc(lambInv, epsilon, stratPar1) frVelCpx = VONKARMANCONST * windCpx /\ (math.log(tmpFrVel / (corPar * roughLength_m)) + math.log(VONKARMANCONST * dH / lambInv) - profileFunc_m) tempScale = VONKARMANCONST * (tempAtm - tempSurf) /\ (math.log(tmpFrVel / (corPar * roughLength_h)) + math.log(VONKARMANCONST * dH / lambInv) - profileFunc_h) else: profileFunc_m = profileFunc_momentum_Calc(lambInv, epsilon, stratPar) profileFunc_h = profileFunc_heat_Calc(lambInv, epsilon, stratPar) Coeff = cmath.tanh((1 + 1j) * (M - epsilon)) Coeff *= (1 - cmath.sinh((1 + 1j) * (M - dH1)) / cmath.sinh((1 + 1j) * (M - epsilon))) A = lambInv * Coeff B = - A + profileFunc_m - math.log(VONKARMANCONST * epsilon / lambInv) C = -2. * lambInv * (dH - epsilon) + profileFunc_h -\ math.log(VONKARMANCONST * epsilon / lambInv) frVelCpx = VONKARMANCONST * windCpx / \ (math.log(tmpFrVel / (corPar * roughLength_m))- B - 1j * A) tempScale = VONKARMANCONST * (tempAtm - tempSurf) /\ (math.log(tmpFrVel / (corPar * roughLength_h)) - C) mistake = abs(tmpFrVelCpx - frVelCpx) / abs(tmpFrVelCpx) tmpFrVelCpx = 0.3 * frVelCpx + 0.7 * tmpFrVelCpx tmpFrVel = abs(tmpFrVelCpx) stratPar = VONKARMANCONST ** 2 * BETA * tempScale / (corPar * tmpFrVel) if it > 100: print 'error in backgroundCalc' break A = lambInv * cmath.tanh((1 + 1j) * (M - epsilon)) B = - A + profileFunc_momentum_Calc(lambInv, epsilon, stratPar) - math.log(VONKARMANCONST * epsilon / lambInv) C = -2 * lambInv * (M - epsilon) + profileFunc_heat_Calc(lambInv, epsilon, stratPar) -\ math.log(VONKARMANCONST * epsilon / lambInv) geostrWindCpx = tmpFrVelCpx / VONKARMANCONST * \ (math.log(tmpFrVel / (corPar * roughLength_m)) - B - 1j * A) tempTop = tempSurf + tempScale / VONKARMANCONST * (math.log(tmpFrVel / (corPar * roughLength_h)) - C) gam = 2 * tempScale * abs(frVelCpx) / EkmanDepth ** 2 / corPar RES = [stratPar, EkmanDepth, frVelCpx, tempScale, roughLength_m, roughLength_h, tempTop, gam, tempSurf, geostrWindCpx] return RES
def tan_impl(z): """cmath.tan(z) = -j * cmath.tanh(z j)""" r = cmath.tanh(complex(-z.imag, z.real)) return complex(r.imag, -r.real)
def tanh_usecase(x): return cmath.tanh(x)
def func_f_plate(self, _omega, _lambda, u): return _omega + sqrt(_lambda*(1-_omega)/3/u)*tanh(sqrt(3*(1-_omega)*u/_lambda))