def test_var(): expr1.convert_to_expr(src, "f") ls = expr1.return_expr() for iter in expr1.return_expr(): assert isinstance(iter, Declaration) assert ls[0] == Declaration( Variable(Symbol("a"), type=IntBaseType(String("integer")), value=Integer(0)) ) assert ls[1] == Declaration( Variable(Symbol("b"), type=IntBaseType(String("integer")), value=Integer(0)) ) assert ls[2] == Declaration( Variable(Symbol("c"), type=IntBaseType(String("integer")), value=Integer(0)) ) assert ls[3] == Declaration( Variable(Symbol("d"), type=IntBaseType(String("integer")), value=Integer(0)) ) assert ls[4] == Declaration( Variable(Symbol("p"), type=FloatBaseType(String("real")), value=Float(0.0)) ) assert ls[5] == Declaration( Variable(Symbol("q"), type=FloatBaseType(String("real")), value=Float(0.0)) ) assert ls[6] == Declaration( Variable(Symbol("r"), type=FloatBaseType(String("real")), value=Float(0.0)) ) assert ls[7] == Declaration( Variable(Symbol("s"), type=FloatBaseType(String("real")), value=Float(0.0)) )
def _eval_evalf(self, prec): """Evaluate this complex root to the given precision. """ _prec, mp.prec = mp.prec, prec try: func = lambdify(self.poly.gen, self.expr) interval = self._get_interval() refined = False while True: if self.is_real: x0 = mpf(str(interval.center)) else: x0 = mpc(*map(str, interval.center)) try: root = findroot(func, x0) except ValueError: interval = interval.refine() refined = True continue else: if refined: self._set_interval(interval) break finally: mp.prec = _prec return Float._new(root.real._mpf_, prec) + I*Float._new(root.imag._mpf_, prec)
def test_c_parse(): src1 = """\ int a, b = 4; float c, d = 2.4; """ expr1.convert_to_expr(src1, "c") ls = expr1.return_expr() assert ls[0] == Declaration( Variable(Symbol("a"), type=IntBaseType(String("integer")), value=Integer(0))) assert ls[1] == Declaration( Variable(Symbol("b"), type=IntBaseType(String("integer")), value=Integer(4))) assert ls[2] == Declaration( Variable( Symbol("c"), type=FloatBaseType(String("real")), value=Float("0.0", precision=53), )) assert ls[3] == Declaration( Variable( Symbol("d"), type=FloatBaseType(String("real")), value=Float("2.3999999999999999", precision=53), ))
def _eval_evalf(self, prec): """Evaluate this complex root to the given precision. """ with workprec(prec): g = self.poly.gen if not g.is_Symbol: d = Dummy('x') func = lambdify(d, self.expr.subs(g, d)) else: func = lambdify(g, self.expr) interval = self._get_interval() if not self.is_real: # For complex intervals, we need to keep refining until the # imaginary interval is disjunct with other roots, that is, # until both ends get refined. ay = interval.ay by = interval.by while interval.ay == ay or interval.by == by: interval = interval.refine() while True: if self.is_real: x0 = mpf(str(interval.center)) else: x0 = mpc(*map(str, interval.center)) try: root = findroot(func, x0, verify=False) # If the (real or complex) root is not in the 'interval', # then keep refining the interval. This happens if findroot # accidentally finds a different root outside of this # interval because our initial estimate 'x0' was not close # enough. if self.is_real: a = mpf(str(interval.a)) b = mpf(str(interval.b)) if a == b: root = a break if not (a < root < b): raise ValueError("Root not in the interval.") else: ax = mpf(str(interval.ax)) bx = mpf(str(interval.bx)) ay = mpf(str(interval.ay)) by = mpf(str(interval.by)) if ax == bx and ay == by: root = ax + S.ImaginaryUnit * by break if not (ax < root.real < bx and ay < root.imag < by): raise ValueError("Root not in the interval.") except ValueError: interval = interval.refine() continue else: break return Float._new(root.real._mpf_, prec) + I * Float._new(root.imag._mpf_, prec)
def _eval_evalf(self, prec): """Evaluate this complex root to the given precision. """ _prec, mp.prec = mp.prec, prec try: func = lambdify(self.poly.gen, self.expr) interval = self._get_interval() if not self.is_real: # For complex intervals, we need to keep refining until the # imaginary interval is disjunct with other roots, that is, # until both ends get refined. ay = interval.ay by = interval.by while interval.ay == ay or interval.by == by: interval = interval.refine() while True: if self.is_real: x0 = mpf(str(interval.center)) else: x0 = mpc(*map(str, interval.center)) try: root = findroot(func, x0) # If the (real or complex) root is not in the 'interval', # then keep refining the interval. This happens if findroot # accidentally finds a different root outside of this # interval because our initial estimate 'x0' was not close # enough. if self.is_real: a = mpf(str(interval.a)) b = mpf(str(interval.b)) # This is needed due to the bug #3364: a, b = min(a, b), max(a, b) if not (a < root < b): raise ValueError("Root not in the interval.") else: ax = mpf(str(interval.ax)) bx = mpf(str(interval.bx)) ay = mpf(str(interval.ay)) by = mpf(str(interval.by)) # This is needed due to the bug #3364: ax, bx = min(ax, bx), max(ax, bx) ay, by = min(ay, by), max(ay, by) if not (ax < root.real < bx and ay < root.imag < by): raise ValueError("Root not in the interval.") except ValueError: interval = interval.refine() continue else: break finally: mp.prec = _prec return Float._new(root.real._mpf_, prec) + I * Float._new(root.imag._mpf_, prec)
def _print_NumberSymbol(self, expr): if self._settings.get("inline", False): return self._print(Float(expr.evalf(self._settings["precision"]))) else: # A Number symbol that is not implemented here or with _printmethod # is registered and evaluated self._number_symbols.add((expr, Float(expr.evalf(self._settings["precision"])))) return str(expr)
def _eval_evalf(self, prec): """Evaluate this complex root to the given precision. """ with workprec(prec): g = self.poly.gen if not g.is_Symbol: d = Dummy('x') func = lambdify(d, self.expr.subs(g, d)) else: func = lambdify(g, self.expr) interval = self._get_interval() if not self.is_real: # For complex intervals, we need to keep refining until the # imaginary interval is disjunct with other roots, that is, # until both ends get refined. ay = interval.ay by = interval.by while interval.ay == ay or interval.by == by: interval = interval.refine() while True: if self.is_real: x0 = mpf(str(interval.center)) else: x0 = mpc(*map(str, interval.center)) try: root = findroot(func, x0, verify=False) # If the (real or complex) root is not in the 'interval', # then keep refining the interval. This happens if findroot # accidentally finds a different root outside of this # interval because our initial estimate 'x0' was not close # enough. if self.is_real: a = mpf(str(interval.a)) b = mpf(str(interval.b)) if a == b: root = a break if not (a < root < b): raise ValueError("Root not in the interval.") else: ax = mpf(str(interval.ax)) bx = mpf(str(interval.bx)) ay = mpf(str(interval.ay)) by = mpf(str(interval.by)) if ax == bx and ay == by: root = ax + S.ImaginaryUnit*by break if not (ax < root.real < bx and ay < root.imag < by): raise ValueError("Root not in the interval.") except ValueError: interval = interval.refine() continue else: break return Float._new(root.real._mpf_, prec) + I*Float._new(root.imag._mpf_, prec)
def _eval_evalf(self, prec): """Evaluate this complex root to the given precision. """ _prec, mp.prec = mp.prec, prec try: func = lambdify(self.poly.gen, self.expr) interval = self._get_interval() if not self.is_real: # For complex intervals, we need to keep refining until the # imaginary interval is disjunct with other roots, that is, # until both ends get refined. ay = interval.ay by = interval.by while interval.ay == ay or interval.by == by: interval = interval.refine() while True: if self.is_real: x0 = mpf(str(interval.center)) else: x0 = mpc(*map(str, interval.center)) try: root = findroot(func, x0) # If the (real or complex) root is not in the 'interval', # then keep refining the interval. This happens if findroot # accidentally finds a different root outside of this # interval because our initial estimate 'x0' was not close # enough. if self.is_real: a = mpf(str(interval.a)) b = mpf(str(interval.b)) # This is needed due to the bug #3364: a, b = min(a, b), max(a, b) if not (a < root < b): raise ValueError("Root not in the interval.") else: ax = mpf(str(interval.ax)) bx = mpf(str(interval.bx)) ay = mpf(str(interval.ay)) by = mpf(str(interval.by)) # This is needed due to the bug #3364: ax, bx = min(ax, bx), max(ax, bx) ay, by = min(ay, by), max(ay, by) if not (ax < root.real < bx and ay < root.imag < by): raise ValueError("Root not in the interval.") except ValueError: interval = interval.refine() continue else: break finally: mp.prec = _prec return Float._new(root.real._mpf_, prec) + I*Float._new(root.imag._mpf_, prec)
def visit_Variable(self, node): """Visitor Function for Variable Declaration Visits each variable declaration present in the ASR and creates a Symbol declaration for each variable Notes ===== The functions currently only support declaration of integer and real variables. Other data types are still under development. Raises ====== NotImplementedError() when called for unsupported data types """ if isinstance(node.type, asr.Integer): var_type = IntBaseType(String('integer')) value = Integer(0) elif isinstance(node.type, asr.Real): var_type = FloatBaseType(String('real')) value = Float(0.0) else: raise NotImplementedError("Data type not supported") if not (node.intent == 'in'): new_node = Variable(node.name).as_Declaration(type=var_type, value=value) self._py_ast.append(new_node)
def test_sympy_parser(): x = Symbol('x') inputs = { '2*x': 2 * x, '3.00': Float(3), '22/7': Rational(22, 7), '2+3j': 2 + 3*I, 'exp(x)': exp(x), 'x!': factorial(x), 'x!!': factorial2(x), '(x + 1)! - 1': factorial(x + 1) - 1, '3.[3]': Rational(10, 3), '.0[3]': Rational(1, 30), '3.2[3]': Rational(97, 30), '1.3[12]': Rational(433, 330), '1 + 3.[3]': Rational(13, 3), '1 + .0[3]': Rational(31, 30), '1 + 3.2[3]': Rational(127, 30), '.[0011]': Rational(1, 909), '0.1[00102] + 1': Rational(366697, 333330), '1.[0191]': Rational(10190, 9999), '10!': 3628800, '-(2)': -Integer(2), '[-1, -2, 3]': [Integer(-1), Integer(-2), Integer(3)], 'Symbol("x").free_symbols': x.free_symbols, "S('S(3).n(n=3)')": 3.00, 'factorint(12, visual=True)': Mul( Pow(2, 2, evaluate=False), Pow(3, 1, evaluate=False), evaluate=False), 'Limit(sin(x), x, 0, dir="-")': Limit(sin(x), x, 0, dir='-'), } for text, result in inputs.items(): assert parse_expr(text) == result
def test_c_parse(): src1 = """\ int a, b = 4; float c, d = 2.4; """ expr1.convert_to_expr(src1, 'c') ls = expr1.return_expr() assert ls[0] == Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')))) assert ls[1] == Declaration( Variable(Symbol('b'), type=IntBaseType(String('intc')), value=Integer(4))) assert ls[2] == Declaration( Variable(Symbol('c'), type=FloatType(String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8)))) assert ls[3] == Declaration( Variable(Symbol('d'), type=FloatType(String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8)), value=Float('2.3999999999999999', precision=53)))
def test_sym_expr(): src1 = (src + """\ d = a + b -c """) expr3 = SymPyExpression(src, 'f') expr4 = SymPyExpression(src1, 'f') ls1 = expr3.return_expr() ls2 = expr4.return_expr() for i in range(0, 7): assert isinstance(ls1[i], Declaration) assert isinstance(ls2[i], Declaration) assert isinstance(ls2[8], Assignment) assert ls1[0] == Declaration( Variable(Symbol('a'), type=IntBaseType(String('integer')), value=Integer(0))) assert ls1[1] == Declaration( Variable(Symbol('b'), type=IntBaseType(String('integer')), value=Integer(0))) assert ls1[2] == Declaration( Variable(Symbol('c'), type=IntBaseType(String('integer')), value=Integer(0))) assert ls1[3] == Declaration( Variable(Symbol('d'), type=IntBaseType(String('integer')), value=Integer(0))) assert ls1[4] == Declaration( Variable(Symbol('p'), type=FloatBaseType(String('real')), value=Float(0.0))) assert ls1[5] == Declaration( Variable(Symbol('q'), type=FloatBaseType(String('real')), value=Float(0.0))) assert ls1[6] == Declaration( Variable(Symbol('r'), type=FloatBaseType(String('real')), value=Float(0.0))) assert ls1[7] == Declaration( Variable(Symbol('s'), type=FloatBaseType(String('real')), value=Float(0.0))) assert ls2[8] == Assignment(Variable(Symbol('d')), Symbol('a') + Symbol('b') - Symbol('c'))
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_fortran_parse(): expr = SymPyExpression(src, "f") ls = expr.return_expr() assert ls[0] == Declaration( Variable(Symbol("a"), type=IntBaseType(String("integer")), value=Integer(0))) assert ls[1] == Declaration( Variable(Symbol("b"), type=IntBaseType(String("integer")), value=Integer(0))) assert ls[2] == Declaration( Variable(Symbol("c"), type=IntBaseType(String("integer")), value=Integer(0))) assert ls[3] == Declaration( Variable(Symbol("d"), type=IntBaseType(String("integer")), value=Integer(0))) assert ls[4] == Declaration( Variable( Symbol("p"), type=FloatBaseType(String("real")), value=Float("0.0", precision=53), )) assert ls[5] == Declaration( Variable( Symbol("q"), type=FloatBaseType(String("real")), value=Float("0.0", precision=53), )) assert ls[6] == Declaration( Variable( Symbol("r"), type=FloatBaseType(String("real")), value=Float("0.0", precision=53), )) assert ls[7] == Declaration( Variable( Symbol("s"), type=FloatBaseType(String("real")), value=Float("0.0", precision=53), ))
def test_sym_expr(): src1 = ( src + """\ d = a + b -c """ ) expr3 = SymPyExpression(src, "f") expr4 = SymPyExpression(src1, "f") ls1 = expr3.return_expr() ls2 = expr4.return_expr() for i in range(0, 7): assert isinstance(ls1[i], Declaration) assert isinstance(ls2[i], Declaration) assert isinstance(ls2[8], Assignment) assert ls1[0] == Declaration( Variable(Symbol("a"), type=IntBaseType(String("integer")), value=Integer(0)) ) assert ls1[1] == Declaration( Variable(Symbol("b"), type=IntBaseType(String("integer")), value=Integer(0)) ) assert ls1[2] == Declaration( Variable(Symbol("c"), type=IntBaseType(String("integer")), value=Integer(0)) ) assert ls1[3] == Declaration( Variable(Symbol("d"), type=IntBaseType(String("integer")), value=Integer(0)) ) assert ls1[4] == Declaration( Variable(Symbol("p"), type=FloatBaseType(String("real")), value=Float(0.0)) ) assert ls1[5] == Declaration( Variable(Symbol("q"), type=FloatBaseType(String("real")), value=Float(0.0)) ) assert ls1[6] == Declaration( Variable(Symbol("r"), type=FloatBaseType(String("real")), value=Float(0.0)) ) assert ls1[7] == Declaration( Variable(Symbol("s"), type=FloatBaseType(String("real")), value=Float(0.0)) ) assert ls2[8] == Assignment( Variable(Symbol("d")), Symbol("a") + Symbol("b") - Symbol("c") )
def _eval_eq_direct(e, subs=None): '''do the actual interval evaluation''' rv = None if not isinstance(e, Expr): raise RuntimeError("Expected sympy Expr: " + repr(e)) if isinstance(e, Symbol): if subs == None: raise RuntimeError("Symbol '" + str(e) + "' found but no substitutions were provided") val = subs.get(str(e)) if val == None: raise RuntimeError("No substitution was provided for symbol '" + str(e) + "'") rv = val elif isinstance(e, Number): rv = interval(Float(e)) elif isinstance(e, Mul): rv = interval(1) for child in e.args: rv *= _eval_eq_direct(child, subs) elif isinstance(e, Add): rv = interval(0) for child in e.args: rv += _eval_eq_direct(child, subs) elif isinstance(e, Pow): term = _eval_eq_direct(e.args[0], subs) exponent = _eval_eq_direct(e.args[1], subs) rv = term**exponent else: # interval function evaluation (like sin) func_map = [(sin, iv.sin), (cos, iv.cos), (tan, iv.tan)] for entry in func_map: t = entry[0] # type f = entry[1] # function to call if isinstance(e, t): inner_arg = _eval_eq_direct(e.args[0], subs) rv = f(inner_arg) break if rv == None: raise RuntimeError("Type '" + str(type(e)) + "' is not yet implemented for interval evaluation. " + \ "Subexpression was '" + str(e) + "'.") return rv
def test_zero(): x = Symbol('x') y = Symbol('y') assert 0**x != 0 assert 0**(2 * x) == 0**x assert 0**(1.0 * x) == 0**x assert 0**(2.0 * x) == 0**x assert (0**(2 - x)).as_base_exp() == (0, 2 - x) assert 0**(x - 2) != S.Infinity**(2 - x) assert 0**(2 * x * y) == 0**(x * y) assert 0**(-2 * x * y) == S.ComplexInfinity**(x * y) assert Float(0)**2 is not S.Zero assert Float(0)**2 == 0.0 assert Float(0)**-2 is zoo assert Float(0)**oo is S.Zero #Test issue 19572 assert 0**-oo is zoo assert power(0, -oo) is zoo assert Float(0)**-oo is zoo
def test_var(): expr1.convert_to_expr(src, 'f') ls = expr1.return_expr() for iter in expr1.return_expr(): assert isinstance(iter, Declaration) assert ls[0] == Declaration( Variable(Symbol('a'), type=IntBaseType(String('integer')), value=Integer(0))) assert ls[1] == Declaration( Variable(Symbol('b'), type=IntBaseType(String('integer')), value=Integer(0))) assert ls[2] == Declaration( Variable(Symbol('c'), type=IntBaseType(String('integer')), value=Integer(0))) assert ls[3] == Declaration( Variable(Symbol('d'), type=IntBaseType(String('integer')), value=Integer(0))) assert ls[4] == Declaration( Variable(Symbol('p'), type=FloatBaseType(String('real')), value=Float(0.0))) assert ls[5] == Declaration( Variable(Symbol('q'), type=FloatBaseType(String('real')), value=Float(0.0))) assert ls[6] == Declaration( Variable(Symbol('r'), type=FloatBaseType(String('real')), value=Float(0.0))) assert ls[7] == Declaration( Variable(Symbol('s'), type=FloatBaseType(String('real')), value=Float(0.0)))
def test_fortran_parse(): expr = SymPyExpression(src, 'f') ls = expr.return_expr() assert ls[0] == Declaration( Variable(Symbol('a'), type=IntBaseType(String('integer')), value=Integer(0))) assert ls[1] == Declaration( Variable(Symbol('b'), type=IntBaseType(String('integer')), value=Integer(0))) assert ls[2] == Declaration( Variable(Symbol('c'), type=IntBaseType(String('integer')), value=Integer(0))) assert ls[3] == Declaration( Variable(Symbol('d'), type=IntBaseType(String('integer')), value=Integer(0))) assert ls[4] == Declaration( Variable(Symbol('p'), type=FloatBaseType(String('real')), value=Float('0.0', precision=53))) assert ls[5] == Declaration( Variable(Symbol('q'), type=FloatBaseType(String('real')), value=Float('0.0', precision=53))) assert ls[6] == Declaration( Variable(Symbol('r'), type=FloatBaseType(String('real')), value=Float('0.0', precision=53))) assert ls[7] == Declaration( Variable(Symbol('s'), type=FloatBaseType(String('real')), value=Float('0.0', precision=53)))
def test_issue_2993(): x = Symbol("x") assert str((2.3 * x - 4)**0.3) == "1.5157165665104*(0.575*x - 1)**0.3" assert str((2.3 * x + 4)**0.3) == "1.5157165665104*(0.575*x + 1)**0.3" assert str((-2.3 * x + 4)**0.3) == "1.5157165665104*(1 - 0.575*x)**0.3" assert str((-2.3 * x - 4)**0.3) == "1.5157165665104*(-0.575*x - 1)**0.3" assert str( (2.3 * x - 2)**0.3) == "1.28386201800527*(x - 0.869565217391304)**0.3" assert (str((-2.3 * x - 2)**0.3) == "1.28386201800527*(-x - 0.869565217391304)**0.3") assert str( (-2.3 * x + 2)**0.3) == "1.28386201800527*(0.869565217391304 - x)**0.3" assert str( (2.3 * x + 2)**0.3) == "1.28386201800527*(x + 0.869565217391304)**0.3" assert str((2.3 * x - 4)**Rational(1, 3)) == "2**(2/3)*(0.575*x - 1)**(1/3)" eq = 2.3 * x + 4 assert eq**2 == 16 * (0.575 * x + 1)**2 assert (1 / eq).args == (eq, -1) # don't change trivial power # issue 17735 q = 0.5 * exp(x) - 0.5 * exp(-x) + 0.1 assert int((q**2).subs(x, 1)) == 1 # issue 17756 y = Symbol("y") assert (len( sqrt(x / (x + y)**2 + Float("0.008", 30)).subs( y, pi.n(25)).atoms(Float)) == 2) # issue 17756 a, b, c, d, e, f, g = symbols("a:g") expr = (sqrt(1 + a * (c**4 + g * d - 2 * g * e - f * (-g + d))**2 / (c**3 * b**2 * (d - 3 * e + 2 * f)**2)) / 2) r = [ (a, N("0.0170992456333788667034850458615", 30)), (b, N("0.0966594956075474769169134801223", 30)), (c, N("0.390911862903463913632151616184", 30)), (d, N("0.152812084558656566271750185933", 30)), (e, N("0.137562344465103337106561623432", 30)), (f, N("0.174259178881496659302933610355", 30)), (g, N("0.220745448491223779615401870086", 30)), ] tru = expr.n(30, subs=dict(r)) seq = expr.subs(r) # although `tru` is the right way to evaluate # expr with numerical values, `seq` will have # significant loss of precision if extraction of # the largest coefficient of a power's base's terms # is done improperly assert seq == tru
def test_sympy_parser(): x = Symbol('x') inputs = { '2*x': 2 * x, '3.00': Float(3), '22/7': Rational(22, 7), '2+3j': 2 + 3*I, 'exp(x)': exp(x), 'x!': factorial(x), '3.[3]': Rational(10, 3), '10!': 3628800, '(_kern)': Symbol('_kern'), '-(2)': -Integer(2), '[-1, -2, 3]': [Integer(-1), Integer(-2), Integer(3)] } for text, result in inputs.items(): assert parse_expr(text) == result
def confidence(s, p): """Return a symmetric (p*100)% confidence interval. For example, p=0.95 gives a 95% confidence interval. Currently this function only handles numerical values except in the trivial case p=1. For example, one standard deviation: >>> from sympy.statistics import Normal >>> N = Normal(0, 1) >>> N.confidence(0.68) (-0.994457883209753, 0.994457883209753) >>> N.probability(*_).evalf() 0.680000000000000 Two standard deviations: >>> N = Normal(0, 1) >>> N.confidence(0.95) (-1.95996398454005, 1.95996398454005) >>> N.probability(*_).evalf() 0.950000000000000 """ if p == 1: return (-oo, oo) if p > 1: raise ValueError("p cannot be greater than 1") # In terms of n*sigma, we have n = sqrt(2)*ierf(p). The inverse # error function is not yet implemented in SymPy but can easily be # computed numerically from sympy.mpmath import mpf, erfinv # calculate y = ierf(p) by solving erf(y) - p = 0 y = erfinv(mpf(p)) t = Float(str(mpf(float(s.sigma)) * mpf(2)**0.5 * y)) mu = s.mu.evalf() return (mu - t, mu + t)
def visit_rlpsum(self, rlpsum): """ Visitor Method, which is called in case the current node of the syntax tree is an instance of a rlpsum :param rlpsum: The current node, which is an instance of a rlpsum :type rlpsum: RLPSum :return: """ answers = self.logkb.ask(rlpsum.query_symbols, rlpsum.query) result = Float(0.0) for answer in answers: expression_eval_subs = rlpsum.expression for index, symbol in enumerate(rlpsum.query_symbols): subanswer = answer[index] expression_eval_subs = expression_eval_subs.subs( symbol, subanswer) # expression_eval_subs = expression_eval_subs.subs(symbol, answer[index]) result += expression_eval_subs return result
def test_sympy_parser(): x = Symbol('x') inputs = { '2*x': 2 * x, '3.00': Float(3), '22/7': Rational(22, 7), '2+3j': 2 + 3*I, 'exp(x)': exp(x), 'x!': factorial(x), '3.[3]': Rational(10, 3), '10!': 3628800, '-(2)': -Integer(2), '[-1, -2, 3]': [Integer(-1), Integer(-2), Integer(3)], 'Symbol("x").free_symbols': x.free_symbols, "S('S(3).n(n=3)')": 3.00, 'factorint(12, visual=True)': Mul( Pow(2, 2, evaluate=False), Pow(3, 1, evaluate=False), evaluate=False), 'Limit(sin(x), x, 0, dir="-")': Limit(sin(x), x, 0, dir='-'), } for text, result in inputs.items(): assert parse_expr(text) == result
def test_C99CodePrinter__precision_f80(): f80_printer = C99CodePrinter(dict(type_aliases={real: float80})) assert f80_printer.doprint(sin(x + Float('2.1'))) == 'sinl(x + 2.1L)'
def _eval_evalf(self, prec): """Evaluate this complex root to the given precision. """ with workprec(prec): g = self.poly.gen if not g.is_Symbol: d = Dummy('x') func = lambdify(d, self.expr.subs(g, d)) else: func = lambdify(g, self.expr) interval = self._get_interval() if not self.is_real: # For complex intervals, we need to keep refining until the # imaginary interval is disjunct with other roots, that is, # until both ends get refined. ay = interval.ay by = interval.by while interval.ay == ay or interval.by == by: interval = interval.refine() while True: if self.is_real: a = mpf(str(interval.a)) b = mpf(str(interval.b)) if a == b: root = a break x0 = mpf(str(interval.center)) else: ax = mpf(str(interval.ax)) bx = mpf(str(interval.bx)) ay = mpf(str(interval.ay)) by = mpf(str(interval.by)) if ax == bx and ay == by: # the sign of the imaginary part will be assigned # according to the desired index using the fact that # roots are sorted with negative imag parts coming # before positive (and all imag roots coming after real # roots) deg = self.poly.degree() i = self.index # a positive attribute after creation if (deg - i) % 2: if ay < 0: ay = -ay else: if ay > 0: ay = -ay root = mpc(ax, ay) break x0 = mpc(*map(str, interval.center)) try: root = findroot(func, x0) # If the (real or complex) root is not in the 'interval', # then keep refining the interval. This happens if findroot # accidentally finds a different root outside of this # interval because our initial estimate 'x0' was not close # enough. It is also possible that the secant method will # get trapped by a max/min in the interval; the root # verification by findroot will raise a ValueError in this # case and the interval will then be tightened -- and # eventually the root will be found. # # It is also possible that findroot will not have any # successful iterations to process (in which case it # will fail to initialize a variable that is tested # after the iterations and raise an UnboundLocalError). if self.is_real: if (a <= root <= b): break elif (ax <= root.real <= bx and ay <= root.imag <= by): break except (UnboundLocalError, ValueError): pass interval = interval.refine() return (Float._new(root.real._mpf_, prec) + I*Float._new(root.imag._mpf_, prec))
def test_negative_real(): def feq(a, b): return abs(a - b) < 1E-10 assert feq(S.One / Float(-0.5), -Integer(2))
def _random(s): return Float(random.uniform(float(s.a), float(s.b)))
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)")
def _print_NumberSymbol(self, expr): # A Number symbol that is not implemented here or with _printmethod # is registered and evaluated self._number_symbols.add( (expr, Float(expr.evalf(self._settings['precision'])))) return str(expr)
def eval_approx(self, n): """Evaluate this complex root to the given precision. This uses secant method and root bounds are used to both generate an initial guess and to check that the root returned is valid. If ever the method converges outside the root bounds, the bounds will be made smaller and updated. """ prec = dps_to_prec(n) with workprec(prec): g = self.poly.gen if not g.is_Symbol: d = Dummy('x') if self.is_imaginary: d *= I func = lambdify(d, self.expr.subs(g, d)) else: expr = self.expr if self.is_imaginary: expr = self.expr.subs(g, I * g) func = lambdify(g, expr) interval = self._get_interval() while True: if self.is_real: a = mpf(str(interval.a)) b = mpf(str(interval.b)) if a == b: root = a break x0 = mpf(str(interval.center)) x1 = x0 + mpf(str(interval.dx)) / 4 elif self.is_imaginary: a = mpf(str(interval.ay)) b = mpf(str(interval.by)) if a == b: root = mpc(mpf('0'), a) break x0 = mpf(str(interval.center[1])) x1 = x0 + mpf(str(interval.dy)) / 4 else: ax = mpf(str(interval.ax)) bx = mpf(str(interval.bx)) ay = mpf(str(interval.ay)) by = mpf(str(interval.by)) if ax == bx and ay == by: root = mpc(ax, ay) break x0 = mpc(*map(str, interval.center)) x1 = x0 + mpc(*map(str, (interval.dx, interval.dy))) / 4 try: # without a tolerance, this will return when (to within # the given precision) x_i == x_{i-1} root = findroot(func, (x0, x1)) # If the (real or complex) root is not in the 'interval', # then keep refining the interval. This happens if findroot # accidentally finds a different root outside of this # interval because our initial estimate 'x0' was not close # enough. It is also possible that the secant method will # get trapped by a max/min in the interval; the root # verification by findroot will raise a ValueError in this # case and the interval will then be tightened -- and # eventually the root will be found. # # It is also possible that findroot will not have any # successful iterations to process (in which case it # will fail to initialize a variable that is tested # after the iterations and raise an UnboundLocalError). if self.is_real or self.is_imaginary: if not bool(root.imag) == self.is_real and (a <= root <= b): if self.is_imaginary: root = mpc(mpf('0'), root.real) break elif (ax <= root.real <= bx and ay <= root.imag <= by): break except (UnboundLocalError, ValueError): pass interval = interval.refine() # update the interval so we at least (for this precision or # less) don't have much work to do to recompute the root self._set_interval(interval) return (Float._new(root.real._mpf_, prec) + I * Float._new(root.imag._mpf_, prec))
def _print_Pow(self, expr): if expr.base.is_integer and not expr.exp.is_integer: expr = type(expr)(Float(expr.base), expr.exp) return self._print(expr) return self._print_Function(expr)
def eval_approx(self, n): """Evaluate this complex root to the given precision. This uses secant method and root bounds are used to both generate an initial guess and to check that the root returned is valid. If ever the method converges outside the root bounds, the bounds will be made smaller and updated. """ prec = dps_to_prec(n) with workprec(prec): g = self.poly.gen if not g.is_Symbol: d = Dummy('x') if self.is_imaginary: d *= I func = lambdify(d, self.expr.subs(g, d)) else: expr = self.expr if self.is_imaginary: expr = self.expr.subs(g, I*g) func = lambdify(g, expr) interval = self._get_interval() while True: if self.is_real: a = mpf(str(interval.a)) b = mpf(str(interval.b)) if a == b: root = a break x0 = mpf(str(interval.center)) x1 = x0 + mpf(str(interval.dx))/4 elif self.is_imaginary: a = mpf(str(interval.ay)) b = mpf(str(interval.by)) if a == b: root = mpc(mpf('0'), a) break x0 = mpf(str(interval.center[1])) x1 = x0 + mpf(str(interval.dy))/4 else: ax = mpf(str(interval.ax)) bx = mpf(str(interval.bx)) ay = mpf(str(interval.ay)) by = mpf(str(interval.by)) if ax == bx and ay == by: root = mpc(ax, ay) break x0 = mpc(*map(str, interval.center)) x1 = x0 + mpc(*map(str, (interval.dx, interval.dy)))/4 try: # without a tolerance, this will return when (to within # the given precision) x_i == x_{i-1} root = findroot(func, (x0, x1)) # If the (real or complex) root is not in the 'interval', # then keep refining the interval. This happens if findroot # accidentally finds a different root outside of this # interval because our initial estimate 'x0' was not close # enough. It is also possible that the secant method will # get trapped by a max/min in the interval; the root # verification by findroot will raise a ValueError in this # case and the interval will then be tightened -- and # eventually the root will be found. # # It is also possible that findroot will not have any # successful iterations to process (in which case it # will fail to initialize a variable that is tested # after the iterations and raise an UnboundLocalError). if self.is_real or self.is_imaginary: if not bool(root.imag) == self.is_real and ( a <= root <= b): if self.is_imaginary: root = mpc(mpf('0'), root.real) break elif (ax <= root.real <= bx and ay <= root.imag <= by): break except (UnboundLocalError, ValueError): pass interval = interval.refine() # update the interval so we at least (for this precision or # less) don't have much work to do to recompute the root self._set_interval(interval) return (Float._new(root.real._mpf_, prec) + I*Float._new(root.imag._mpf_, prec))