def test_PythonCodePrinter(): prntr = PythonCodePrinter() assert not prntr.module_imports assert prntr.doprint(x**y) == "x**y" assert prntr.doprint(Mod(x, 2)) == "x % 2" assert prntr.doprint(And(x, y)) == "x and y" assert prntr.doprint(Or(x, y)) == "x or y" assert not prntr.module_imports assert prntr.doprint(pi) == "math.pi" assert prntr.module_imports == {"math": {"pi"}} assert prntr.doprint(x**Rational(1, 2)) == "math.sqrt(x)" assert prntr.doprint(sqrt(x)) == "math.sqrt(x)" assert prntr.module_imports == {"math": {"pi", "sqrt"}} assert prntr.doprint(acos(x)) == "math.acos(x)" assert prntr.doprint(Assignment(x, 2)) == "x = 2" assert (prntr.doprint(Piecewise( (1, Eq(x, 0)), (2, x > 6))) == "((1) if (x == 0) else (2) if (x > 6) else None)") assert (prntr.doprint( Piecewise((2, Le(x, 0)), (3, Gt(x, 0)), evaluate=False)) == "((2) if (x <= 0) else" " (3) if (x > 0) else None)") assert prntr.doprint(sign(x)) == "(0.0 if x == 0 else math.copysign(1, x))" assert prntr.doprint(p[0, 1]) == "p[0, 1]"
def test_PythonCodePrinter(): prntr = PythonCodePrinter() assert not prntr.module_imports assert prntr.doprint(x**y) == 'x**y' assert prntr.doprint(Mod(x, 2)) == 'x % 2' assert prntr.doprint(And(x, y)) == 'x and y' assert prntr.doprint(Or(x, y)) == 'x or y' assert not prntr.module_imports assert prntr.doprint(pi) == 'math.pi' assert prntr.module_imports == {'math': {'pi'}} assert prntr.doprint(x**Rational(1, 2)) == 'math.sqrt(x)' assert prntr.doprint(sqrt(x)) == 'math.sqrt(x)' assert prntr.module_imports == {'math': {'pi', 'sqrt'}} assert prntr.doprint(acos(x)) == 'math.acos(x)' assert prntr.doprint(Assignment(x, 2)) == 'x = 2' assert prntr.doprint(Piecewise( (1, Eq(x, 0)), (2, x > 6))) == '((1) if (x == 0) else (2) if (x > 6) else None)' assert prntr.doprint(Piecewise((2, Le(x, 0)), (3, Gt(x, 0)), evaluate=False)) == '((2) if (x <= 0) else'\ ' (3) if (x > 0) else None)' assert prntr.doprint(sign(x)) == '(0.0 if x == 0 else math.copysign(1, x))' assert prntr.doprint(p[0, 1]) == 'p[0, 1]'
def roots_cubic(f, trig=False): """Returns a list of roots of a cubic polynomial.""" if trig: a, b, c, d = f.all_coeffs() p = (3*a*c - b**2)/3/a**2 q = (2*b**3 - 9*a*b*c + 27*a**2*d)/(27*a**3) D = 18*a*b*c*d - 4*b**3*d + b**2*c**2 - 4*a*c**3 - 27*a**2*d**2 if (D > 0) == True: rv = [] for k in range(3): rv.append(2*sqrt(-p/3)*cos(acos(3*q/2/p*sqrt(-3/p))/3 - k*2*pi/3)) return [i - b/3/a for i in rv] _, a, b, c = f.monic().all_coeffs() if c is S.Zero: x1, x2 = roots([1, a, b], multiple=True) return [x1, S.Zero, x2] p = b - a**2/3 q = c - a*b/3 + 2*a**3/27 pon3 = p/3 aon3 = a/3 if p is S.Zero: if q is S.Zero: return [-aon3]*3 else: if q.is_real: if (q > 0) == True: u1 = -root(q, 3) else: u1 = root(-q, 3) else: u1 = root(-q, 3) elif q is S.Zero: y1, y2 = roots([1, 0, p], multiple=True) return [tmp - aon3 for tmp in [y1, S.Zero, y2]] elif q.is_real and q < 0: u1 = -root(-q/2 + sqrt(q**2/4 + pon3**3), 3) else: u1 = root(q/2 + sqrt(q**2/4 + pon3**3), 3) coeff = I*sqrt(3)/2 u2 = u1*(-S.Half + coeff) u3 = u1*(-S.Half - coeff) if p is S.Zero: return [u1 - aon3, u2 - aon3, u3 - aon3] soln = [ -u1 + pon3/u1 - aon3, -u2 + pon3/u2 - aon3, -u3 + pon3/u3 - aon3 ] return soln
def angle(vec1, vec2, vec3=None): if vec3 is None: return acos(dot(normalize(vec1), normalize(vec2))) else: if dot(cross(vec1, vec2), vec3) > 0: return angle(cross(vec1, vec3), cross(vec2, vec3)) else: return 2*pi-angle(cross(vec1, vec3), cross(vec2, vec3))
def roots_cubic(f, trig=False): """Returns a list of roots of a cubic polynomial.""" if trig: a, b, c, d = f.all_coeffs() p = (3 * a * c - b**2) / 3 / a**2 q = (2 * b**3 - 9 * a * b * c + 27 * a**2 * d) / (27 * a**3) D = 18 * a * b * c * d - 4 * b**3 * d + b**2 * c**2 - 4 * a * c**3 - 27 * a**2 * d**2 if (D > 0) == True: rv = [] for k in range(3): rv.append(2 * sqrt(-p / 3) * cos( acos(3 * q / 2 / p * sqrt(-3 / p)) / 3 - k * 2 * pi / 3)) return list(sorted([i - b / 3 / a for i in rv])) _, a, b, c = f.monic().all_coeffs() if c is S.Zero: x1, x2 = roots([1, a, b], multiple=True) return [x1, S.Zero, x2] p = b - a**2 / 3 q = c - a * b / 3 + 2 * a**3 / 27 pon3 = p / 3 aon3 = a / 3 if p is S.Zero: if q is S.Zero: return [-aon3] * 3 else: if q.is_real: if (q > 0) == True: u1 = -q**Rational(1, 3) else: u1 = (-q)**Rational(1, 3) else: u1 = (-q)**Rational(1, 3) elif q is S.Zero: y1, y2 = roots([1, 0, p], multiple=True) return [tmp - aon3 for tmp in [y1, S.Zero, y2]] elif q.is_real and q < 0: u1 = -(-q / 2 + sqrt(q**2 / 4 + pon3**3))**Rational(1, 3) else: u1 = (q / 2 + sqrt(q**2 / 4 + pon3**3))**Rational(1, 3) coeff = S.ImaginaryUnit * sqrt(3) / 2 u2 = u1 * (-S.Half + coeff) u3 = u1 * (-S.Half - coeff) if p is S.Zero: return [u1 - aon3, u2 - aon3, u3 - aon3] soln = [ -u1 + pon3 / u1 - aon3, -u2 + pon3 / u2 - aon3, -u3 + pon3 / u3 - aon3 ] return soln
def rmat_k2d(d): d = normalize(d) if d == k: rot = eye(3) elif d == -k: rot = diag(1,-1,-1) else: rot = rquat2rmat(rquat(acos(dot(k, d)), cross(k, d))) return rot
def test_C99CodePrinter__precision(): n = symbols('n', integer=True) f32_printer = C99CodePrinter(dict(type_aliases={real: float32})) f64_printer = C99CodePrinter(dict(type_aliases={real: float64})) f80_printer = C99CodePrinter(dict(type_aliases={real: float80})) assert f32_printer.doprint(sin(x+2.1)) == 'sinf(x + 2.1F)' assert f64_printer.doprint(sin(x+2.1)) == 'sin(x + 2.1000000000000001)' assert f80_printer.doprint(sin(x+Float('2.0'))) == 'sinl(x + 2.0L)' for printer, suffix in zip([f32_printer, f64_printer, f80_printer], ['f', '', 'l']): def check(expr, ref): assert printer.doprint(expr) == ref.format(s=suffix, S=suffix.upper()) check(Abs(n), 'abs(n)') check(Abs(x + 2.0), 'fabs{s}(x + 2.0{S})') check(sin(x + 4.0)**cos(x - 2.0), 'pow{s}(sin{s}(x + 4.0{S}), cos{s}(x - 2.0{S}))') check(exp(x*8.0), 'exp{s}(8.0{S}*x)') check(exp2(x), 'exp2{s}(x)') check(expm1(x*4.0), 'expm1{s}(4.0{S}*x)') check(Mod(n, 2), '((n) % (2))') check(Mod(2*n + 3, 3*n + 5), '((2*n + 3) % (3*n + 5))') check(Mod(x + 2.0, 3.0), 'fmod{s}(1.0{S}*x + 2.0{S}, 3.0{S})') check(Mod(x, 2.0*x + 3.0), 'fmod{s}(1.0{S}*x, 2.0{S}*x + 3.0{S})') check(log(x/2), 'log{s}((1.0{S}/2.0{S})*x)') check(log10(3*x/2), 'log10{s}((3.0{S}/2.0{S})*x)') check(log2(x*8.0), 'log2{s}(8.0{S}*x)') check(log1p(x), 'log1p{s}(x)') check(2**x, 'pow{s}(2, x)') check(2.0**x, 'pow{s}(2.0{S}, x)') check(x**3, 'pow{s}(x, 3)') check(x**4.0, 'pow{s}(x, 4.0{S})') check(sqrt(3+x), 'sqrt{s}(x + 3)') check(Cbrt(x-2.0), 'cbrt{s}(x - 2.0{S})') check(hypot(x, y), 'hypot{s}(x, y)') check(sin(3.*x + 2.), 'sin{s}(3.0{S}*x + 2.0{S})') check(cos(3.*x - 1.), 'cos{s}(3.0{S}*x - 1.0{S})') check(tan(4.*y + 2.), 'tan{s}(4.0{S}*y + 2.0{S})') check(asin(3.*x + 2.), 'asin{s}(3.0{S}*x + 2.0{S})') check(acos(3.*x + 2.), 'acos{s}(3.0{S}*x + 2.0{S})') check(atan(3.*x + 2.), 'atan{s}(3.0{S}*x + 2.0{S})') check(atan2(3.*x, 2.*y), 'atan2{s}(3.0{S}*x, 2.0{S}*y)') check(sinh(3.*x + 2.), 'sinh{s}(3.0{S}*x + 2.0{S})') check(cosh(3.*x - 1.), 'cosh{s}(3.0{S}*x - 1.0{S})') check(tanh(4.0*y + 2.), 'tanh{s}(4.0{S}*y + 2.0{S})') check(asinh(3.*x + 2.), 'asinh{s}(3.0{S}*x + 2.0{S})') check(acosh(3.*x + 2.), 'acosh{s}(3.0{S}*x + 2.0{S})') check(atanh(3.*x + 2.), 'atanh{s}(3.0{S}*x + 2.0{S})') check(erf(42.*x), 'erf{s}(42.0{S}*x)') check(erfc(42.*x), 'erfc{s}(42.0{S}*x)') check(gamma(x), 'tgamma{s}(x)') check(loggamma(x), 'lgamma{s}(x)') check(ceiling(x + 2.), "ceil{s}(x + 2.0{S})") check(floor(x + 2.), "floor{s}(x + 2.0{S})") check(fma(x, y, -z), 'fma{s}(x, y, -z)') check(Max(x, 8.0, x**4.0), 'fmax{s}(8.0{S}, fmax{s}(x, pow{s}(x, 4.0{S})))') check(Min(x, 2.0), 'fmin{s}(2.0{S}, x)')
def test_C99CodePrinter__precision(): n = symbols('n', integer=True) f32_printer = C99CodePrinter(dict(type_aliases={real: float32})) f64_printer = C99CodePrinter(dict(type_aliases={real: float64})) f80_printer = C99CodePrinter(dict(type_aliases={real: float80})) assert f32_printer.doprint(sin(x+2.1)) == 'sinf(x + 2.1F)' assert f64_printer.doprint(sin(x+2.1)) == 'sin(x + 2.1000000000000001)' assert f80_printer.doprint(sin(x+Float('2.0'))) == 'sinl(x + 2.0L)' for printer, suffix in zip([f32_printer, f64_printer, f80_printer], ['f', '', 'l']): def check(expr, ref): assert printer.doprint(expr) == ref.format(s=suffix, S=suffix.upper()) check(Abs(n), 'abs(n)') check(Abs(x + 2.0), 'fabs{s}(x + 2.0{S})') check(sin(x + 4.0)**cos(x - 2.0), 'pow{s}(sin{s}(x + 4.0{S}), cos{s}(x - 2.0{S}))') check(exp(x*8.0), 'exp{s}(8.0{S}*x)') check(exp2(x), 'exp2{s}(x)') check(expm1(x*4.0), 'expm1{s}(4.0{S}*x)') check(Mod(n, 2), '((n) % (2))') check(Mod(2*n + 3, 3*n + 5), '((2*n + 3) % (3*n + 5))') check(Mod(x + 2.0, 3.0), 'fmod{s}(1.0{S}*x + 2.0{S}, 3.0{S})') check(Mod(x, 2.0*x + 3.0), 'fmod{s}(1.0{S}*x, 2.0{S}*x + 3.0{S})') check(log(x/2), 'log{s}((1.0{S}/2.0{S})*x)') check(log10(3*x/2), 'log10{s}((3.0{S}/2.0{S})*x)') check(log2(x*8.0), 'log2{s}(8.0{S}*x)') check(log1p(x), 'log1p{s}(x)') check(2**x, 'pow{s}(2, x)') check(2.0**x, 'pow{s}(2.0{S}, x)') check(x**3, 'pow{s}(x, 3)') check(x**4.0, 'pow{s}(x, 4.0{S})') check(sqrt(3+x), 'sqrt{s}(x + 3)') check(Cbrt(x-2.0), 'cbrt{s}(x - 2.0{S})') check(hypot(x, y), 'hypot{s}(x, y)') check(sin(3.*x + 2.), 'sin{s}(3.0{S}*x + 2.0{S})') check(cos(3.*x - 1.), 'cos{s}(3.0{S}*x - 1.0{S})') check(tan(4.*y + 2.), 'tan{s}(4.0{S}*y + 2.0{S})') check(asin(3.*x + 2.), 'asin{s}(3.0{S}*x + 2.0{S})') check(acos(3.*x + 2.), 'acos{s}(3.0{S}*x + 2.0{S})') check(atan(3.*x + 2.), 'atan{s}(3.0{S}*x + 2.0{S})') check(atan2(3.*x, 2.*y), 'atan2{s}(3.0{S}*x, 2.0{S}*y)') check(sinh(3.*x + 2.), 'sinh{s}(3.0{S}*x + 2.0{S})') check(cosh(3.*x - 1.), 'cosh{s}(3.0{S}*x - 1.0{S})') check(tanh(4.0*y + 2.), 'tanh{s}(4.0{S}*y + 2.0{S})') check(asinh(3.*x + 2.), 'asinh{s}(3.0{S}*x + 2.0{S})') check(acosh(3.*x + 2.), 'acosh{s}(3.0{S}*x + 2.0{S})') check(atanh(3.*x + 2.), 'atanh{s}(3.0{S}*x + 2.0{S})') check(erf(42.*x), 'erf{s}(42.0{S}*x)') check(erfc(42.*x), 'erfc{s}(42.0{S}*x)') check(gamma(x), 'tgamma{s}(x)') check(loggamma(x), 'lgamma{s}(x)') check(ceiling(x + 2.), "ceil{s}(x + 2.0{S})") check(floor(x + 2.), "floor{s}(x + 2.0{S})") check(fma(x, y, -z), 'fma{s}(x, y, -z)') check(Max(x, 8.0, x**4.0), 'fmax{s}(8.0{S}, fmax{s}(x, pow{s}(x, 4.0{S})))') check(Min(x, 2.0), 'fmin{s}(2.0{S}, x)')
def test_SciPyPrinter(): p = SciPyPrinter() expr = acos(x) assert 'numpy' not in p.module_imports assert p.doprint(expr) == 'numpy.arccos(x)' assert 'numpy' in p.module_imports assert not any(m.startswith('scipy') for m in p.module_imports) smat = SparseMatrix(2, 5, {(0, 1): 3}) assert p.doprint(smat) == 'scipy.sparse.coo_matrix([3], ([0], [1]), shape=(2, 5))' assert 'scipy.sparse' in p.module_imports
def test_SciPyPrinter(): p = SciPyPrinter() expr = acos(x) assert 'numpy' not in p.module_imports assert p.doprint(expr) == 'numpy.arccos(x)' assert 'numpy' in p.module_imports assert not any(m.startswith('scipy') for m in p.module_imports) smat = SparseMatrix(2, 5, {(0, 1): 3}) assert p.doprint(smat) == 'scipy.sparse.coo_matrix([3], ([0], [1]), shape=(2, 5))' assert 'scipy.sparse' in p.module_imports
def test_PythonCodePrinter(): prntr = PythonCodePrinter() assert not prntr.module_imports assert prntr.doprint(x**y) == 'x**y' assert prntr.doprint(Mod(x, 2)) == 'x % 2' assert prntr.doprint(And(x, y)) == 'x and y' assert prntr.doprint(Or(x, y)) == 'x or y' assert not prntr.module_imports assert prntr.doprint(pi) == 'math.pi' assert prntr.module_imports == {'math': {'pi'}} assert prntr.doprint(acos(x)) == 'math.acos(x)'
def test_PythonCodePrinter(): prntr = PythonCodePrinter() assert not prntr.module_imports assert prntr.doprint(x**y) == 'x**y' assert prntr.doprint(Mod(x, 2)) == 'x % 2' assert prntr.doprint(And(x, y)) == 'x and y' assert prntr.doprint(Or(x, y)) == 'x or y' assert not prntr.module_imports assert prntr.doprint(pi) == 'math.pi' assert prntr.module_imports == {'math': {'pi'}} assert prntr.doprint(acos(x)) == 'math.acos(x)' assert prntr.doprint(Assignment(x, 2)) == 'x = 2'
def test_SciPyPrinter(): p = SciPyPrinter() expr = acos(x) assert 'numpy' not in p.module_imports assert p.doprint(expr) == 'numpy.arccos(x)' assert 'numpy' in p.module_imports assert not any(m.startswith('scipy') for m in p.module_imports) smat = SparseMatrix(2, 5, {(0, 1): 3}) assert p.doprint(smat) == \ 'scipy.sparse.coo_matrix(([3], ([0], [1])), shape=(2, 5))' assert 'scipy.sparse' in p.module_imports assert p.doprint(S.GoldenRatio) == 'scipy.constants.golden_ratio' assert p.doprint(S.Pi) == 'scipy.constants.pi' assert p.doprint(S.Exp1) == 'numpy.e'
def test_SciPyPrinter(): p = SciPyPrinter() expr = acos(x) assert "numpy" not in p.module_imports assert p.doprint(expr) == "numpy.arccos(x)" assert "numpy" in p.module_imports assert not any(m.startswith("scipy") for m in p.module_imports) smat = SparseMatrix(2, 5, {(0, 1): 3}) assert p.doprint( smat) == "scipy.sparse.coo_matrix([3], ([0], [1]), shape=(2, 5))" assert "scipy.sparse" in p.module_imports assert p.doprint(S.GoldenRatio) == "scipy.constants.golden_ratio" assert p.doprint(S.Pi) == "scipy.constants.pi" assert p.doprint(S.Exp1) == "numpy.e"
def test_PythonCodePrinter(): prntr = PythonCodePrinter() assert not prntr.module_imports assert prntr.doprint(x**y) == 'x**y' assert prntr.doprint(Mod(x, 2)) == 'x % 2' assert prntr.doprint(And(x, y)) == 'x and y' assert prntr.doprint(Or(x, y)) == 'x or y' assert not prntr.module_imports assert prntr.doprint(pi) == 'math.pi' assert prntr.module_imports == {'math': {'pi'}} assert prntr.doprint(acos(x)) == 'math.acos(x)' assert prntr.doprint(Assignment(x, 2)) == 'x = 2' assert prntr.doprint(Piecewise((1, Eq(x, 0)), (2, x>6))) == '((1) if (x == 0) else (2) if (x > 6) else None)' assert prntr.doprint(Piecewise((2, Le(x, 0)), (3, Gt(x, 0)), evaluate=False)) == '((2) if (x <= 0) else'\ ' (3) if (x > 0) else None)' assert prntr.doprint(sign(x)) == '(0.0 if x == 0 else math.copysign(1, x))'
def _invert_real(f, g_ys, symbol): """ Helper function for invert_real """ if not f.has(symbol): raise ValueError("Inverse of constant function doesn't exist") if f is symbol: return (f, g_ys) n = Dummy('n') if hasattr(f, 'inverse') and not isinstance(f, TrigonometricFunction) and \ not isinstance(f, HyperbolicFunction): if len(f.args) > 1: raise ValueError("Only functions with one argument are supported.") return _invert_real(f.args[0], imageset(Lambda(n, f.inverse()(n)), g_ys), symbol) if isinstance(f, Abs): return _invert_real( f.args[0], Union( imageset(Lambda(n, n), g_ys).intersect(Interval(0, oo)), imageset(Lambda(n, -n), g_ys).intersect(Interval(-oo, 0))), symbol) if f.is_Add: # f = g + h g, h = f.as_independent(symbol) if g != S.Zero: return _invert_real(h, imageset(Lambda(n, n - g), g_ys), symbol) if f.is_Mul: # f = g*h g, h = f.as_independent(symbol) if g != S.One: return _invert_real(h, imageset(Lambda(n, n / g), g_ys), symbol) if f.is_Pow: base, expo = f.args base_has_sym = base.has(symbol) expo_has_sym = expo.has(symbol) if not expo_has_sym: res = imageset(Lambda(n, real_root(n, expo)), g_ys) if expo.is_rational: numer, denom = expo.as_numer_denom() if numer == S.One or numer == -S.One: return _invert_real(base, res, symbol) else: if numer % 2 == 0: n = Dummy('n') neg_res = imageset(Lambda(n, -n), res) return _invert_real(base, res + neg_res, symbol) else: return _invert_real(base, res, symbol) else: if not base.is_positive: raise ValueError("x**w where w is irrational is not " "defined for negative x") return _invert_real(base, res, symbol) if not base_has_sym: return _invert_real(expo, imageset(Lambda(n, log(n) / log(base)), g_ys), symbol) if isinstance(f, sin): n = Dummy('n') if isinstance(g_ys, FiniteSet): sin_invs = Union(*[imageset(Lambda(n, n*pi + (-1)**n*asin(g_y)), \ S.Integers) for g_y in g_ys]) return _invert_real(f.args[0], sin_invs, symbol) if isinstance(f, csc): n = Dummy('n') if isinstance(g_ys, FiniteSet): csc_invs = Union(*[imageset(Lambda(n, n*pi + (-1)**n*acsc(g_y)), \ S.Integers) for g_y in g_ys]) return _invert_real(f.args[0], csc_invs, symbol) if isinstance(f, cos): n = Dummy('n') if isinstance(g_ys, FiniteSet): cos_invs_f1 = Union(*[imageset(Lambda(n, 2*n*pi + acos(g_y)), \ S.Integers) for g_y in g_ys]) cos_invs_f2 = Union(*[imageset(Lambda(n, 2*n*pi - acos(g_y)), \ S.Integers) for g_y in g_ys]) cos_invs = Union(cos_invs_f1, cos_invs_f2) return _invert_real(f.args[0], cos_invs, symbol) if isinstance(f, sec): n = Dummy('n') if isinstance(g_ys, FiniteSet): sec_invs_f1 = Union(*[imageset(Lambda(n, 2*n*pi + asec(g_y)), \ S.Integers) for g_y in g_ys]) sec_invs_f2 = Union(*[imageset(Lambda(n, 2*n*pi - asec(g_y)), \ S.Integers) for g_y in g_ys]) sec_invs = Union(sec_invs_f1, sec_invs_f2) return _invert_real(f.args[0], sec_invs, symbol) if isinstance(f, tan) or isinstance(f, cot): n = Dummy('n') if isinstance(g_ys, FiniteSet): tan_cot_invs = Union(*[imageset(Lambda(n, n*pi + f.inverse()(g_y)), \ S.Integers) for g_y in g_ys]) return _invert_real(f.args[0], tan_cot_invs, symbol) return (f, g_ys)
def test_tensorflow_math(): if not tf: skip("TensorFlow not installed") expr = Abs(x) assert tensorflow_code(expr) == "tensorflow.math.abs(x)" _compare_tensorflow_scalar((x, ), expr) expr = sign(x) assert tensorflow_code(expr) == "tensorflow.math.sign(x)" _compare_tensorflow_scalar((x, ), expr) expr = ceiling(x) assert tensorflow_code(expr) == "tensorflow.math.ceil(x)" _compare_tensorflow_scalar((x, ), expr, rng=lambda: random.random()) expr = floor(x) assert tensorflow_code(expr) == "tensorflow.math.floor(x)" _compare_tensorflow_scalar((x, ), expr, rng=lambda: random.random()) expr = exp(x) assert tensorflow_code(expr) == "tensorflow.math.exp(x)" _compare_tensorflow_scalar((x, ), expr, rng=lambda: random.random()) expr = sqrt(x) assert tensorflow_code(expr) == "tensorflow.math.sqrt(x)" _compare_tensorflow_scalar((x, ), expr, rng=lambda: random.random()) expr = x**4 assert tensorflow_code(expr) == "tensorflow.math.pow(x, 4)" _compare_tensorflow_scalar((x, ), expr, rng=lambda: random.random()) expr = cos(x) assert tensorflow_code(expr) == "tensorflow.math.cos(x)" _compare_tensorflow_scalar((x, ), expr, rng=lambda: random.random()) expr = acos(x) assert tensorflow_code(expr) == "tensorflow.math.acos(x)" _compare_tensorflow_scalar((x, ), expr, rng=lambda: random.uniform(0, 0.95)) expr = sin(x) assert tensorflow_code(expr) == "tensorflow.math.sin(x)" _compare_tensorflow_scalar((x, ), expr, rng=lambda: random.random()) expr = asin(x) assert tensorflow_code(expr) == "tensorflow.math.asin(x)" _compare_tensorflow_scalar((x, ), expr, rng=lambda: random.random()) expr = tan(x) assert tensorflow_code(expr) == "tensorflow.math.tan(x)" _compare_tensorflow_scalar((x, ), expr, rng=lambda: random.random()) expr = atan(x) assert tensorflow_code(expr) == "tensorflow.math.atan(x)" _compare_tensorflow_scalar((x, ), expr, rng=lambda: random.random()) expr = atan2(y, x) assert tensorflow_code(expr) == "tensorflow.math.atan2(y, x)" _compare_tensorflow_scalar((y, x), expr, rng=lambda: random.random()) expr = cosh(x) assert tensorflow_code(expr) == "tensorflow.math.cosh(x)" _compare_tensorflow_scalar((x, ), expr, rng=lambda: random.random()) expr = acosh(x) assert tensorflow_code(expr) == "tensorflow.math.acosh(x)" _compare_tensorflow_scalar((x, ), expr, rng=lambda: random.uniform(1, 2)) expr = sinh(x) assert tensorflow_code(expr) == "tensorflow.math.sinh(x)" _compare_tensorflow_scalar((x, ), expr, rng=lambda: random.uniform(1, 2)) expr = asinh(x) assert tensorflow_code(expr) == "tensorflow.math.asinh(x)" _compare_tensorflow_scalar((x, ), expr, rng=lambda: random.uniform(1, 2)) expr = tanh(x) assert tensorflow_code(expr) == "tensorflow.math.tanh(x)" _compare_tensorflow_scalar((x, ), expr, rng=lambda: random.uniform(1, 2)) expr = atanh(x) assert tensorflow_code(expr) == "tensorflow.math.atanh(x)" _compare_tensorflow_scalar((x, ), expr, rng=lambda: random.uniform(-.5, .5)) expr = erf(x) assert tensorflow_code(expr) == "tensorflow.math.erf(x)" _compare_tensorflow_scalar((x, ), expr, rng=lambda: random.random()) expr = loggamma(x) assert tensorflow_code(expr) == "tensorflow.math.lgamma(x)" _compare_tensorflow_scalar((x, ), expr, rng=lambda: random.random())
def _invert_real(f, g_ys, symbol): """ Helper function for invert_real """ if not f.has(symbol): raise ValueError("Inverse of constant function doesn't exist") if f is symbol: return (f, g_ys) n = Dummy('n') if hasattr(f, 'inverse') and not isinstance(f, TrigonometricFunction) and \ not isinstance(f, HyperbolicFunction): if len(f.args) > 1: raise ValueError("Only functions with one argument are supported.") return _invert_real(f.args[0], imageset(Lambda(n, f.inverse()(n)), g_ys), symbol) if isinstance(f, Abs): return _invert_real(f.args[0], Union(imageset(Lambda(n, n), g_ys).intersect(Interval(0, oo)), imageset(Lambda(n, -n), g_ys).intersect(Interval(-oo, 0))), symbol) if f.is_Add: # f = g + h g, h = f.as_independent(symbol) if g != S.Zero: return _invert_real(h, imageset(Lambda(n, n - g), g_ys), symbol) if f.is_Mul: # f = g*h g, h = f.as_independent(symbol) if g != S.One: return _invert_real(h, imageset(Lambda(n, n/g), g_ys), symbol) if f.is_Pow: base, expo = f.args base_has_sym = base.has(symbol) expo_has_sym = expo.has(symbol) if not expo_has_sym: res = imageset(Lambda(n, real_root(n, expo)), g_ys) if expo.is_rational: numer, denom = expo.as_numer_denom() if numer == S.One or numer == - S.One: return _invert_real(base, res, symbol) else: if numer % 2 == 0: n = Dummy('n') neg_res = imageset(Lambda(n, -n), res) return _invert_real(base, res + neg_res, symbol) else: return _invert_real(base, res, symbol) else: if not base.is_positive: raise ValueError("x**w where w is irrational is not " "defined for negative x") return _invert_real(base, res, symbol) if not base_has_sym: return _invert_real(expo, imageset(Lambda(n, log(n)/log(base)), g_ys), symbol) if isinstance(f, sin): n = Dummy('n') if isinstance(g_ys, FiniteSet): sin_invs = Union(*[imageset(Lambda(n, n*pi + (-1)**n*asin(g_y)), \ S.Integers) for g_y in g_ys]) return _invert_real(f.args[0], sin_invs, symbol) if isinstance(f, csc): n = Dummy('n') if isinstance(g_ys, FiniteSet): csc_invs = Union(*[imageset(Lambda(n, n*pi + (-1)**n*acsc(g_y)), \ S.Integers) for g_y in g_ys]) return _invert_real(f.args[0], csc_invs, symbol) if isinstance(f, cos): n = Dummy('n') if isinstance(g_ys, FiniteSet): cos_invs_f1 = Union(*[imageset(Lambda(n, 2*n*pi + acos(g_y)), \ S.Integers) for g_y in g_ys]) cos_invs_f2 = Union(*[imageset(Lambda(n, 2*n*pi - acos(g_y)), \ S.Integers) for g_y in g_ys]) cos_invs = Union(cos_invs_f1, cos_invs_f2) return _invert_real(f.args[0], cos_invs, symbol) if isinstance(f, sec): n = Dummy('n') if isinstance(g_ys, FiniteSet): sec_invs_f1 = Union(*[imageset(Lambda(n, 2*n*pi + asec(g_y)), \ S.Integers) for g_y in g_ys]) sec_invs_f2 = Union(*[imageset(Lambda(n, 2*n*pi - asec(g_y)), \ S.Integers) for g_y in g_ys]) sec_invs = Union(sec_invs_f1, sec_invs_f2) return _invert_real(f.args[0], sec_invs, symbol) if isinstance(f, tan) or isinstance(f, cot): n = Dummy('n') if isinstance(g_ys, FiniteSet): tan_cot_invs = Union(*[imageset(Lambda(n, n*pi + f.inverse()(g_y)), \ S.Integers) for g_y in g_ys]) return _invert_real(f.args[0], tan_cot_invs, symbol) return (f, g_ys)
def test_jscode_functions(): assert jscode(sin(x) ** cos(x)) == "Math.pow(Math.sin(x), Math.cos(x))" assert jscode(sinh(x) * cosh(x)) == "Math.sinh(x)*Math.cosh(x)" assert jscode(Max(x, y) + Min(x, y)) == "Math.max(x, y) + Math.min(x, y)" assert jscode(tanh(x)*acosh(y)) == "Math.tanh(x)*Math.acosh(y)" assert jscode(asin(x)-acos(y)) == "-Math.acos(y) + Math.asin(x)"
def test_jscode_functions(): assert jscode(sin(x)**cos(x)) == "Math.pow(Math.sin(x), Math.cos(x))" assert jscode(sinh(x) * cosh(x)) == "Math.sinh(x)*Math.cosh(x)" assert jscode(Max(x, y) + Min(x, y)) == "Math.max(x, y) + Math.min(x, y)" assert jscode(tanh(x) * acosh(y)) == "Math.tanh(x)*Math.acosh(y)" assert jscode(asin(x) - acos(y)) == "-Math.acos(y) + Math.asin(x)"
def test_C99CodePrinter__precision(): n = symbols("n", integer=True) f32_printer = C99CodePrinter(dict(type_aliases={real: float32})) f64_printer = C99CodePrinter(dict(type_aliases={real: float64})) f80_printer = C99CodePrinter(dict(type_aliases={real: float80})) assert f32_printer.doprint(sin(x + 2.1)) == "sinf(x + 2.1F)" assert f64_printer.doprint(sin(x + 2.1)) == "sin(x + 2.1000000000000001)" assert f80_printer.doprint(sin(x + Float("2.0"))) == "sinl(x + 2.0L)" for printer, suffix in zip([f32_printer, f64_printer, f80_printer], ["f", "", "l"]): def check(expr, ref): assert printer.doprint(expr) == ref.format(s=suffix, S=suffix.upper()) check(Abs(n), "abs(n)") check(Abs(x + 2.0), "fabs{s}(x + 2.0{S})") check( sin(x + 4.0) ** cos(x - 2.0), "pow{s}(sin{s}(x + 4.0{S}), cos{s}(x - 2.0{S}))", ) check(exp(x * 8.0), "exp{s}(8.0{S}*x)") check(exp2(x), "exp2{s}(x)") check(expm1(x * 4.0), "expm1{s}(4.0{S}*x)") check(Mod(n, 2), "((n) % (2))") check(Mod(2 * n + 3, 3 * n + 5), "((2*n + 3) % (3*n + 5))") check(Mod(x + 2.0, 3.0), "fmod{s}(1.0{S}*x + 2.0{S}, 3.0{S})") check(Mod(x, 2.0 * x + 3.0), "fmod{s}(1.0{S}*x, 2.0{S}*x + 3.0{S})") check(log(x / 2), "log{s}((1.0{S}/2.0{S})*x)") check(log10(3 * x / 2), "log10{s}((3.0{S}/2.0{S})*x)") check(log2(x * 8.0), "log2{s}(8.0{S}*x)") check(log1p(x), "log1p{s}(x)") check(2 ** x, "pow{s}(2, x)") check(2.0 ** x, "pow{s}(2.0{S}, x)") check(x ** 3, "pow{s}(x, 3)") check(x ** 4.0, "pow{s}(x, 4.0{S})") check(sqrt(3 + x), "sqrt{s}(x + 3)") check(Cbrt(x - 2.0), "cbrt{s}(x - 2.0{S})") check(hypot(x, y), "hypot{s}(x, y)") check(sin(3.0 * x + 2.0), "sin{s}(3.0{S}*x + 2.0{S})") check(cos(3.0 * x - 1.0), "cos{s}(3.0{S}*x - 1.0{S})") check(tan(4.0 * y + 2.0), "tan{s}(4.0{S}*y + 2.0{S})") check(asin(3.0 * x + 2.0), "asin{s}(3.0{S}*x + 2.0{S})") check(acos(3.0 * x + 2.0), "acos{s}(3.0{S}*x + 2.0{S})") check(atan(3.0 * x + 2.0), "atan{s}(3.0{S}*x + 2.0{S})") check(atan2(3.0 * x, 2.0 * y), "atan2{s}(3.0{S}*x, 2.0{S}*y)") check(sinh(3.0 * x + 2.0), "sinh{s}(3.0{S}*x + 2.0{S})") check(cosh(3.0 * x - 1.0), "cosh{s}(3.0{S}*x - 1.0{S})") check(tanh(4.0 * y + 2.0), "tanh{s}(4.0{S}*y + 2.0{S})") check(asinh(3.0 * x + 2.0), "asinh{s}(3.0{S}*x + 2.0{S})") check(acosh(3.0 * x + 2.0), "acosh{s}(3.0{S}*x + 2.0{S})") check(atanh(3.0 * x + 2.0), "atanh{s}(3.0{S}*x + 2.0{S})") check(erf(42.0 * x), "erf{s}(42.0{S}*x)") check(erfc(42.0 * x), "erfc{s}(42.0{S}*x)") check(gamma(x), "tgamma{s}(x)") check(loggamma(x), "lgamma{s}(x)") check(ceiling(x + 2.0), "ceil{s}(x + 2.0{S})") check(floor(x + 2.0), "floor{s}(x + 2.0{S})") check(fma(x, y, -z), "fma{s}(x, y, -z)") check(Max(x, 8.0, x ** 4.0), "fmax{s}(8.0{S}, fmax{s}(x, pow{s}(x, 4.0{S})))") check(Min(x, 2.0), "fmin{s}(2.0{S}, x)")
from sympy.simplify import simplify from sympy.solvers import solve from sympy.geometry import Line,Point,intersection from sympy.core import pi,symbols,Symbol,S,N from sympy.functions import sqrt,acos,log,sin,cos,exp import numpy import math #init_printing() print numpy.arccos(-1) print math.acos(-1) print acos(-1) print acos(0) print acos(0) print acos(S.One/2) x,y,z = symbols('x,y,z') alpha,beta,gamma = symbols('alpha,beta,gamma') print x+1 print log(alpha ** beta) + gamma print sin(x)**2 + cos(x)**2 print simplify(sin(x)**2 + cos(x)**2) mu,sigma = symbols('mu,sigma') bell = exp(-(x-mu)**2 / 2*sigma**2) print bell.diff(x) print bell.diff(sigma)
def roots_cubic(f, trig=False): """Returns a list of roots of a cubic polynomial. References ========== [1] https://en.wikipedia.org/wiki/Cubic_function, General formula for roots, (accessed November 17, 2014). """ if trig: a, b, c, d = f.all_coeffs() p = (3*a*c - b**2)/3/a**2 q = (2*b**3 - 9*a*b*c + 27*a**2*d)/(27*a**3) D = 18*a*b*c*d - 4*b**3*d + b**2*c**2 - 4*a*c**3 - 27*a**2*d**2 if (D > 0) == True: rv = [] for k in range(3): rv.append(2*sqrt(-p/3)*cos(acos(3*q/2/p*sqrt(-3/p))/3 - k*2*pi/3)) return [i - b/3/a for i in rv] _, a, b, c = f.monic().all_coeffs() if c is S.Zero: x1, x2 = roots([1, a, b], multiple=True) return [x1, S.Zero, x2] p = b - a**2/3 q = c - a*b/3 + 2*a**3/27 pon3 = p/3 aon3 = a/3 u1 = None if p is S.Zero: if q is S.Zero: return [-aon3]*3 if q.is_real: if q.is_positive: u1 = -root(q, 3) elif q.is_negative: u1 = root(-q, 3) elif q is S.Zero: y1, y2 = roots([1, 0, p], multiple=True) return [tmp - aon3 for tmp in [y1, S.Zero, y2]] elif q.is_real and q.is_negative: u1 = -root(-q/2 + sqrt(q**2/4 + pon3**3), 3) coeff = I*sqrt(3)/2 if u1 is None: u1 = S(1) u2 = -S.Half + coeff u3 = -S.Half - coeff a, b, c, d = S(1), a, b, c D0 = b**2 - 3*a*c D1 = 2*b**3 - 9*a*b*c + 27*a**2*d C = root((D1 + sqrt(D1**2 - 4*D0**3))/2, 3) return [-(b + uk*C + D0/C/uk)/3/a for uk in [u1, u2, u3]] u2 = u1*(-S.Half + coeff) u3 = u1*(-S.Half - coeff) if p is S.Zero: return [u1 - aon3, u2 - aon3, u3 - aon3] soln = [ -u1 + pon3/u1 - aon3, -u2 + pon3/u2 - aon3, -u3 + pon3/u3 - aon3 ] return soln
def test_torch_math(): if not torch: skip("Torch not installed") ma = torch.tensor([[1, 2, -3, -4]]) expr = Abs(x) assert torch_code(expr) == "torch.abs(x)" f = lambdify(x, expr, 'torch') y = f(ma) c = torch.abs(ma) assert (y == c).all() expr = sign(x) assert torch_code(expr) == "torch.sign(x)" _compare_torch_scalar((x, ), expr, rng=lambda: random.randint(0, 10)) expr = ceiling(x) assert torch_code(expr) == "torch.ceil(x)" _compare_torch_scalar((x, ), expr, rng=lambda: random.random()) expr = floor(x) assert torch_code(expr) == "torch.floor(x)" _compare_torch_scalar((x, ), expr, rng=lambda: random.random()) expr = exp(x) assert torch_code(expr) == "torch.exp(x)" _compare_torch_scalar((x, ), expr, rng=lambda: random.random()) # expr = sqrt(x) # assert torch_code(expr) == "torch.sqrt(x)" # _compare_torch_scalar((x,), expr, rng=lambda: random.random()) # expr = x ** 4 # assert torch_code(expr) == "torch.pow(x, 4)" # _compare_torch_scalar((x,), expr, rng=lambda: random.random()) expr = cos(x) assert torch_code(expr) == "torch.cos(x)" _compare_torch_scalar((x, ), expr, rng=lambda: random.random()) expr = acos(x) assert torch_code(expr) == "torch.acos(x)" _compare_torch_scalar((x, ), expr, rng=lambda: random.uniform(0, 0.95)) expr = sin(x) assert torch_code(expr) == "torch.sin(x)" _compare_torch_scalar((x, ), expr, rng=lambda: random.random()) expr = asin(x) assert torch_code(expr) == "torch.asin(x)" _compare_torch_scalar((x, ), expr, rng=lambda: random.random()) expr = tan(x) assert torch_code(expr) == "torch.tan(x)" _compare_torch_scalar((x, ), expr, rng=lambda: random.random()) expr = atan(x) assert torch_code(expr) == "torch.atan(x)" _compare_torch_scalar((x, ), expr, rng=lambda: random.random()) # expr = atan2(y, x) # assert torch_code(expr) == "torch.atan2(y, x)" # _compare_torch_scalar((y, x), expr, rng=lambda: random.random()) expr = cosh(x) assert torch_code(expr) == "torch.cosh(x)" _compare_torch_scalar((x, ), expr, rng=lambda: random.random()) expr = acosh(x) assert torch_code(expr) == "torch.acosh(x)" _compare_torch_scalar((x, ), expr, rng=lambda: random.uniform(1, 2)) expr = sinh(x) assert torch_code(expr) == "torch.sinh(x)" _compare_torch_scalar((x, ), expr, rng=lambda: random.uniform(1, 2)) expr = asinh(x) assert torch_code(expr) == "torch.asinh(x)" _compare_torch_scalar((x, ), expr, rng=lambda: random.uniform(1, 2)) expr = tanh(x) assert torch_code(expr) == "torch.tanh(x)" _compare_torch_scalar((x, ), expr, rng=lambda: random.uniform(1, 2)) expr = atanh(x) assert torch_code(expr) == "torch.atanh(x)" _compare_torch_scalar((x, ), expr, rng=lambda: random.uniform(-.5, .5)) expr = erf(x) assert torch_code(expr) == "torch.erf(x)" _compare_torch_scalar((x, ), expr, rng=lambda: random.random()) expr = loggamma(x) assert torch_code(expr) == "torch.lgamma(x)" _compare_torch_scalar((x, ), expr, rng=lambda: random.random())