def test11_hyp(): for i in range(-5, 5): for j in range(-5, 5): a = ek.sinh(C(i, j)) b = C(cmath.sinh(complex(i, j))) assert ek.allclose(a, b) a = ek.cosh(C(i, j)) b = C(cmath.cosh(complex(i, j))) assert ek.allclose(a, b) sa, ca = ek.sincosh(C(i, j)) sb = C(cmath.sinh(complex(i, j))) cb = C(cmath.cosh(complex(i, j))) assert ek.allclose(sa, sb) assert ek.allclose(ca, cb) # Python appears to handle the branch cuts # differently from Enoki, C, and Mathematica.. a = ek.asinh(C(i + 0.1, j)) b = C(cmath.asinh(complex(i + 0.1, j))) assert ek.allclose(a, b) a = ek.acosh(C(i, j)) b = C(cmath.acosh(complex(i, j))) assert ek.allclose(a, b, atol=1e-7) if abs(i) != 1 or j != 0: a = ek.atanh(C(i, j)) b = C(cmath.atanh(complex(i, j))) assert ek.allclose(a, b, atol=1e-7)
def test_areal_inverses(): assert asin(mpf(0)) == 0 assert asinh(mpf(0)) == 0 assert acosh(mpf(1)) == 0 assert isinstance(asin(mpf(0.5)), mpf) assert isinstance(asin(mpf(2.0)), mpc) assert isinstance(acos(mpf(0.5)), mpf) assert isinstance(acos(mpf(2.0)), mpc) assert isinstance(atanh(mpf(0.1)), mpf) assert isinstance(atanh(mpf(1.1)), mpc) random.seed(1) for i in range(50): x = random.uniform(0, 1) assert asin(mpf(x)).ae(math.asin(x)) assert acos(mpf(x)).ae(math.acos(x)) x = random.uniform(-10, 10) assert asinh(mpf(x)).ae(cmath.asinh(x).real) assert isinstance(asinh(mpf(x)), mpf) x = random.uniform(1, 10) assert acosh(mpf(x)).ae(cmath.acosh(x).real) assert isinstance(acosh(mpf(x)), mpf) x = random.uniform(-10, 0.999) assert isinstance(acosh(mpf(x)), mpc) x = random.uniform(-1, 1) assert atanh(mpf(x)).ae(cmath.atanh(x).real) assert isinstance(atanh(mpf(x)), mpf)
def test_complex_inverse_functions(): mp.dps = 15 iv.dps = 15 for (z1, z2) in random_complexes(30): # apparently cmath uses a different branch, so we # can't use it for comparison assert sinh(asinh(z1)).ae(z1) # assert acosh(z1).ae(cmath.acosh(z1)) assert atanh(z1).ae(cmath.atanh(z1)) assert atan(z1).ae(cmath.atan(z1)) # the reason we set a big eps here is that the cmath # functions are inaccurate assert asin(z1).ae(cmath.asin(z1), rel_eps=1e-12) assert acos(z1).ae(cmath.acos(z1), rel_eps=1e-12) one = mpf(1) for i in range(-9, 10, 3): for k in range(-9, 10, 3): a = 0.9*j*10**k + 0.8*one*10**i b = cos(acos(a)) assert b.ae(a) b = sin(asin(a)) assert b.ae(a) one = mpf(1) err = 2*10**-15 for i in range(-9, 9, 3): for k in range(-9, 9, 3): a = -0.9*10**k + j*0.8*one*10**i b = cosh(acosh(a)) assert b.ae(a, err) b = sinh(asinh(a)) assert b.ae(a, err)
def test_complex_inverse_functions(): mp.dps = 15 iv.dps = 15 for (z1, z2) in random_complexes(30): # apparently cmath uses a different branch, so we # can't use it for comparison assert sinh(asinh(z1)).ae(z1) # assert acosh(z1).ae(cmath.acosh(z1)) assert atanh(z1).ae(cmath.atanh(z1)) assert atan(z1).ae(cmath.atan(z1)) # the reason we set a big eps here is that the cmath # functions are inaccurate assert asin(z1).ae(cmath.asin(z1), rel_eps=1e-12) assert acos(z1).ae(cmath.acos(z1), rel_eps=1e-12) one = mpf(1) for i in range(-9, 10, 3): for k in range(-9, 10, 3): a = 0.9 * j * 10**k + 0.8 * one * 10**i b = cos(acos(a)) assert b.ae(a) b = sin(asin(a)) assert b.ae(a) one = mpf(1) err = 2 * 10**-15 for i in range(-9, 9, 3): for k in range(-9, 9, 3): a = -0.9 * 10**k + j * 0.8 * one * 10**i b = cosh(acosh(a)) assert b.ae(a, err) b = sinh(asinh(a)) assert b.ae(a, err)
def Zin(Zl, Zo, B, l, a=0): """ Impedância de entrada (Meios com ou sem perdas) Obs : Para meios sem perdas, o valor de a é definido em 0 e pode ser deixado em branco Parâmetros ---------- Zl : Imp. característica do meio 2 Zo : Imp. característica do meio 1 B : Constante de fase da onda l : Distância do ponto de encontro entre os dois meios e o ponto de visão relativo da impedância a : Constante de atenuação da onda Retorna a impedância de entrada no formato cartesiano (alfa + jBeta) """ z = a + B * 1j x = cmath.atanh(z * l) x = Zo * (Zl + Zo * x) / (Zo + Zl * x) helper.prettyPrint(x, ["Impedância de entrada"]) return x
def op_atanh(x): """Returns the inverse hyperbolic tangent of this mathematical object.""" if isinstance(x, list): return [op_atanh(a) for a in x] elif isinstance(x, complex): return cmath.atanh(x) else: return math.atanh(x)
def atan_impl(z): """cmath.atan(z) = -j * cmath.atanh(z j)""" r = cmath.atanh(complex(-z.imag, z.real)) if math.isinf(z.real) and math.isnan(z.imag): # XXX this is odd but necessary return complex(r.imag, r.real) else: return complex(r.imag, -r.real)
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 ATANH(df, price='Close'): """ Inverse Hyperbolic Tangent """ atanh_list = [] i = 0 while i < len(df[price]): atanh = cmath.atanh(df[price][i]).real atanh_list.append(atanh) i += 1 return atanh_list
def atanh(z): """ An AlComplex compatible hyperbolic arctangent function. It gets the main value. Parameters ---------- z : Python numeric type or AlComplex Returns ------- AlComplex """ return AlComplex.from_python_complex(cm.atanh(z.to_python_complex()))
def rescaling( x, n , c = 0.9999999999, W = [0,255] ): D = [-n*2**15,n*2**15] w = W[1]-W[0] # lengthe of range d = D[1]-D[0] # length of domain T = 2 * atanh(2*c-1) # upper bound where 100*c % of the limit can theoretically be achieved t = (x-D[0])/d * 2*T - T # rescaling the domain, so it matches to [-T,T] y = ((exp(t)/(1+exp(t))) * w + W[0])/c return real(y)
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 do_func(self, funcstr, x): return eval( funcstr, { "x": x, "e": cmath.e, "pi": cmath.pi, "i": 1j, "exp": cmath.exp, "sin": cmath.sin, "cos": cmath.cos, "tan": cmath.tan, "sinh": cmath.sinh, "cosh": cmath.cosh, "tanh": cmath.tanh, "sec": lambda x: 1 / cmath.cos(x), "csc": lambda x: 1 / cmath.sin(x), "cot": lambda x: cmath.cos(x) / cmath.sin(x), "sech": lambda x: 1 / cmath.cosh(x), "csch": lambda x: 1 / cmath.sinh(x), "coth": lambda x: cmath.cosh(x) / cmath.sinh(x), "arcsin": cmath.asin, "arccos": cmath.acos, "arctan": cmath.atan, "arsinh": cmath.asinh, "arcosh": cmath.acosh, "artanh": cmath.atanh, "arcsec": lambda x: cmath.acos(1 / x), "arccsc": lambda x: cmath.asin(1 / x), "arccot": lambda x: cmath.atan(1 / x), "arsech": lambda x: cmath.acosh(1 / x), "arcsch": lambda x: cmath.asinh(1 / x), "arcoth": lambda x: cmath.atanh(1 / x), "abs": abs, "sgn": sign, "arg": cmath.phase, "cis": lambda x: cmath.cos(x) + 1j * cmath.sin(x), "pow": pow, "sqrt": cmath.sqrt, "nrt": lambda x, n: x**(1 / n), "log": cmath.log, "ln": lambda x: cmath.log(x), "floor": math.floor, "ceil": math.ceil, "trunc": math.trunc, "round": round, "gamma": math_gamma, "weierstrauss": math_weierstrauss, "choose": math_choose, "max": max, "min": min }, {})
def atanh(x): """ Return the inverse 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 = atanh(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./(x**2 - 1)] qc_wrt_args = [2*x/(x**4 - 2*x**2 + 1)] 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 [atanh(xi) for xi in x] # except TypeError: if x.imag: return cmath.atanh(x) else: return math.atanh(x.real)
def atanh(x): """ Return the inverse 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 = atanh(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. / (x**2 - 1)] qc_wrt_args = [2 * x / (x**4 - 2 * x**2 + 1)] 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 [atanh(xi) for xi in x] # except TypeError: if x.imag: return cmath.atanh(x) else: return math.atanh(x.real)
def atanh(x): """ Uncertain number hyperbolic arctangent function .. note:: In the complex case there are two branch cuts: one extends from 1 along the real axis to :math:`\infty`, continuous from below; the other extends from -1 along the real axis to :math:`-\infty`, continuous from above. """ try: return x._atanh() except AttributeError: if isinstance(x, numbers.Real): return math.atanh(x) elif isinstance(x, numbers.Complex): return cmath.atanh(x) else: raise TypeError("illegal argument: {!r}".format(x))
def atanh_usecase(x): return cmath.atanh(x)
def atanh(x): if is_complex(x): return cmath.atanh(x) return math.atanh(x)
def test_atanh(self): self.assertAlmostEqual(complex(0.11750, 1.40992), cmath.atanh(complex(3, 4)))
def testAtanhSign(self): for z in complex_zeros: self.assertComplexIdentical(cmath.atanh(z), z)
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 assert round(1.5) == 2 assert round(-1.5) == -2 assert abs(round(0.25,1) - 0.3) < 1e-14 assert abs(round(1.123456789,4) - 1.1235) < 1e-14
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 assert round(1.5) == 2 assert round(-1.5) == -2 assert abs(round(0.25, 1) - 0.3) < 1e-14 assert abs(round(1.123456789, 4) - 1.1235) < 1e-14
def atanh(x): if isinstance(x, complex): return cmath.atanh(x) else: return math.atanh(x)
# trigonometric functions c = 2 + 2j print('arc sine =', cmath.asin(c)) 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("The tangent value of complex number is : ") print(cmath.tan(z)) print("The arc sine value of complex number is : ") print(cmath.asin(z)) print("The arc cosine value of complex number is : ") print(cmath.acos(z)) print("The arc tangent value of complex number is : ") print(cmath.atan(z)) print("The hyperbolic sine value of complex number is : ") print(cmath.sinh(z)) print("The hyperbolic cosine value of complex number is : ") print(cmath.cosh(z)) print("The hyperbolic tangent value of complex number is : ") print(cmath.tanh(z)) print("The inverse hyperbolic sine value of complex number is : ") print(cmath.asinh(z)) print("The inverse hyperbolic cosine value of complex number is : ") print(cmath.acosh(z)) print("The inverse hyperbolic tangent value of complex number is : ") print(cmath.atanh(z))
def ATANH(df, price='Close'): """ Inverse Hyperbolic Tangent Returns: list of floats = jhta.ATANH(df, price='Close') """ return [cmath.atanh(df[price][i]).real for i in range(len(df[price]))]
def p(self, q, w): q = abs(q) x = w/(self.nu_max*q) # dimensionless constant #return 3j*x**2/(2*w)*( (1j*pi-2*atanh(x))*(1/x-x) - 2 ) return 3j/(2*(self.nu_max*q))*( (1j*pi-2*cmath.atanh(x))*(1-x**2) - 2*x) # nicer form for w=0
# trigonometric functions c = 2 + 2j print('arc sine =', cmath.asin(c)) 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
'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 while i < len(phrase): match = re.match('((sum.+?,).+,.+?\))', phrase[i:]) if match: i += len(match.groups(0)[1]) - 1 match = re.match(function_pattern, phrase[i:]) if match:
def arctanh(self): comp_value = cmath.atanh(self.comp_value) dx1 = 1 - self.comp_value**2 dxr = 1 / dx1 comp_unc = self.comp_unc * dxr # if y = atanh(x) than U(y) = U(x) 1/1-x^2 return Ucom(comp_value, comp_unc, self.name, self.dep)
def nfwshear(theta, nfwpars, zcluster, zsource, cc): """ return the tangential shear of a source galaxy at z=zsource expected assuming a NFW profile with parameters=nfwpars when the galaxy is at radial angular distance=theta (in arcmin) from the center of a galaxy cluster at z=zcluster Assumes a circularly symmetric NFW profile with parameters in dictionary variable nfwpars, and a cosmology (number, dict, number, number, cosmologyCalculator) -> number (list|array|number, dict, number, list|array|number, cosmologyCalculator) -> list|array|number theta: angular distance in arcmin nfwpars: dictionary containing M200 and concentration zcluster: redshift of cluster zsource: redshift of background source cc: cosmology calculator class Assumes flat universe and LCDM Checked against Sarah's matlab code """ # unpack cosmological model, only implemented OmegaM for now if (cc.isClosed() or cc.isOpen()): print 'SIS shear model not implemented for non-flat universes yet!', print 'OmegaK = ',cc.omegaCurv return -99 if (not cc.isLambda): print 'SIS shear model not implemented for non-LCDM universes yet!', print 'w0 = ',cc.wX,'wa =',cc.wXa return -99 # unpack NFW model m200 = nfwpars["M200"] conc = nfwpars["c"] #print 'NFW model: m200 =',m200,' c =',conc # unpack cosmological model, only implemented OmegaM for now OmegaM = cc.omegamat OmegaQ = 1. - OmegaM w0 = -1. wa = 0. h = 1. cc.sethubble(h) # all in h units # mean density at cluster redshift z_plus1_cubed = (1.+zcluster)*(1.+zcluster)*(1.+zcluster) rho_m_zclust = const.rho_crit*OmegaM*z_plus1_cubed #print 'rho_crit =',const.rho_crit,', zcluster =',zcluster #print 'rho_m(z_clust) =',rho_m_zclust # return Hubble distance c/H0 in Mpc/h Dh = cc.DH() # LENS QUANITITES cc.setEmissionRedShift(zcluster) # angular diameter distance etc to lens Mpc/h Dd = cc.AngularDiameterDistanceMpc() # transverse comoving distance to lens Mpc/h Dm_lens = cc.TransComovDistanceMpc() # NFW model delta_c = 200./3.*conc*conc*conc / (math.log(1.+conc) - conc/(1.+conc)) rho_s = delta_c*rho_m_zclust r200 = math.pow(m200/(200.*rho_m_zclust*4./3.*const.pi),1./3.) theta200 = (r200/Dd) *180./const.pi*60 # r200 in theta in arcmin r_s = r200/conc #print 'NFW model parameters: delta_c =',delta_c,' rho_s =',rho_s,'r200 =',r200, #print 'theta200 =',theta200,'r_s =',r_s wasNum = False if (isinstance(zsource, (int, long, float, complex))): # if single z # SOURCE QUANTITIES cc.setEmissionRedShift(zsource) # angular diameter distance etc to source Mpc/h (don't actually need this) Ds = cc.AngularDiameterDistanceMpc() # transverse comoving distance to source Mpc/h Dm_source = cc.TransComovDistanceMpc() # Angular diameter distance between lens and source sqrt1 = Dm_source*math.sqrt(1.+cc.omegaCurv*Dm_lens*Dm_lens/(Dh*Dh)) sqrt2 = Dm_lens*math.sqrt(1.+cc.omegaCurv*Dm_source*Dm_source/(Dh*Dh)) Dds = (sqrt1 - sqrt2)/(1.+zsource) wasNum = True else: # if list/array of z Ds = np.zeros([len(zsource)]) Dds = np.zeros([len(zsource)]) theta_hold = np.zeros([len(zsource)]) i = 0 for zs in zsource: # SOURCE QUANTITIES cc.setEmissionRedShift(zs) # angular diameter distance etc to source Mpc/h Ds[i] = cc.AngularDiameterDistanceMpc() # transverse comoving distance to source Mpc/h Dm_source = cc.TransComovDistanceMpc() # Angular diameter distance between lens and source sqrt1 = Dm_source*math.sqrt(1.+cc.omegaCurv*Dm_lens*Dm_lens/(Dh*Dh)) sqrt2 = Dm_lens*math.sqrt(1.+cc.omegaCurv*Dm_source*Dm_source/(Dh*Dh)) Dds[i] = (sqrt1 - sqrt2)/(1.+zs) theta_hold[i] = theta[i] i+=1 theta = theta_hold # sigma crit in Msolar/Mpc^2 sig_crit = cosmocalcs.Sigma_crit_Msolar_Mpcsq(zcluster, zsource, cc) #sig_crit = cosmocalcs.Sigma_crit(zcluster, zsource, 100., OmegaM, OmegaQ, w0, wa)/const.msolarKg #print 'Sigma_crit =',sig_crit # dimensionless lens parameter x = theta*(1./60.)*(const.pi/180.)*(Dd/r_s) #print 'x =',x #print 'If x=1: kappa =',2.*r_s*rho_s/sig_crit/3. #print 'If x=1: mod_gamma =', r_s*rho_s/sig_crit*(10./3. + 4.*math.log(0.5)) if (wasNum): xvals = np.zeros([1]) kappa = np.zeros([1]) mod_gamma = np.zeros([1]) xvals[0] = x sc = sig_crit sig_crit = np.zeros([1]) sig_crit[0] = sc else: xvals = x kappa = np.zeros([len(x)]) mod_gamma = np.zeros([len(x)]) #print type(xvals) i=0 for x in xvals: # kappa and gamma if (x<1.): #print 'x<1' kappa[i] = 2.*r_s*rho_s/sig_crit[i]/(x*x-1.)*(1. - 2./math.sqrt(1 - x*x) \ *math.atanh(math.sqrt( (1-x)/(1+x) )) ) mod_gamma[i] = r_s*rho_s/sig_crit[i]*(4./(x*x)*math.log(x/2.) - 2./(x*x-1) \ + 4.*math.atanh(math.sqrt((1-x)/(1+x)))*(2 - 3*x*x) \ / (x*x*math.sqrt((1-x*x)*(1-x*x)*(1-x*x))) ) elif (x == 1.): #print 'x=1' kappa[i] = 2.*r_s*rho_s/sig_crit[i]/3. mod_gamma[i] = r_s*rho_s/sig_crit[i]*(10./3. + 4.*math.log(0.5)) elif (x>1.): #print 'x>1' k = 2.*r_s*rho_s/sig_crit[i]/(x*x - 1.)*(1. - 2./math.sqrt(x*x - 1) \ *math.atan(math.sqrt((x-1.)/(1.+x) )) ) kappa[i] = k mod_gamma_atan = (r_s*rho_s/sig_crit[i]*(4./(x*x)*math.log(x/2.) - 2./(x*x-1) \ + 4.*math.atan(math.sqrt((x-1.)/(1.+x)))*(2. - 3.*x*x) \ / (x*x*math.sqrt(pow(x*x-1.,3))) ) ) # something doesn't seem to work right with atan, so use atanh # and take real part (imaginary parts of the below are zero anyway). mod_gamma_complex = r_s*rho_s/sig_crit[i]*(4./(x*x)*math.log(x/2.) - 2./(x*x-1) \ + 4.*cmath.atanh(cmath.sqrt((1.-x)/(1.+x)))*(2. - 3.*x*x) \ / ( x*x*cmath.exp(1.5*cmath.log(1.-x*x))) ) if (abs(mod_gamma_complex.imag))>1e-6: print 'WARNING! Complex part might be large',abs(mod_gamma_complex.imag) mod_gamma[i] = mod_gamma_complex.real i+=1 #print mod_gamma,type(mod_gamma),mod_gamma_atan,type(mod_gamma_atan) if (wasNum): mod_gamma = mod_gamma[0] kappa = kappa[0] # NB. this agrees with numerical integration of kappa values too return mod_gamma, kappa
Power and Log Functions The cmath() module provides some useful functions for logarithmic and power operations. """ c = 1+2j print('e^c = ', cmath.exp(c)) print('log2(c) = ', cmath.log(c,2)) print('log10(c) = ', cmath.log10(c)) print('sqrt(c) = ', cmath.sqrt(c)) """ Trigonometric Functions """ c = 2+4j print('arc sine value:\n ', cmath.asin(c)) print('arc cosine value:\n ', cmath.acos(c)) print('arc tangent value:\n ', cmath.atan(c)) print('sine value:\n ', cmath.sin(c)) print('cosine value:\n ', cmath.cos(c)) print('tangent value:\n ', cmath.tan(c)) """ Hyperbolic Functions """ c = 2+4j print('Inverse hyperbolic sine value: \n', cmath.asinh(c)) print('Inverse hyperbolic cosine value: \n', cmath.acosh(c)) print('Inverse hyperbolic tangent value: \n', cmath.atanh(c)) print('Inverse sine value: \n', cmath.sinh(c)) print('Inverse cosine value: \n', cmath.cosh(c)) print('Inverse tangent value: \n', cmath.tanh(c))
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