def calcular(request): # print dir(request) datos = request.GET print datos.get('lx') print datos.get('ly') res = "<!DOCTYPE html><html><head><title>Lagrange</title><script type='text/javascript' src='/static/MathJax.js?config=TeX-AMS_HTML'></script></head><body><div ><hr>" xl = (datos.get('lx')).split(",") yl = (datos.get('ly')).split(",") for i in range(len(xl)): xl[i] = int(xl[i]) yl[i] = int(yl[i]) lagrange = 0 x = symbols('x') for j in range(len(yl)): lx = 1 for i in range(len(xl)): if j != i: lx = lx * ((x - xl[i]) / (xl[j] - xl[i])) #lx=together(apart(lx,x),x) #res=res+latex(lx, mode='equation')+"<br>" #res=res+"<hr>" res = res + " multiplicando por " + str(yl[j]) + "<br>" lx = lx * yl[j] lx = together(apart(lx, x), x) res = res + latex(lx, mode='equation') + "<br>" res = res + "<hr>" res = res + "<br>" lagrange = lagrange + lx res = res + "La funcion resultado es:<br>" lagrange = together(apart(lagrange, x), x) lista = [] for i in range(1, 21): lista.append(lagrange.subs(x, i)) res = res + latex(lagrange, mode='equation') + "<br>" res = res + "<div><canvas id='lineChart' height='140'></canvas></div></div><script src='/static/jquery-2.1.1.js'></script><script src='/static/chartJs/Chart.min.js'></script>" res = res + """ <script>$(function () {var lineData = { labels: ["1", "2", "3", "4", "5", "6", "7","8","9","10","11","12","13","14","15","16","17","18","19","20"], datasets: [{ label: "funcion",backgroundColor: 'rgba(26,179,148,0.5)', borderColor: "rgba(26,179,148,0.7)",pointBackgroundColor: "rgba(26,179,148,1)", pointBorderColor: "#fff",data: """ + lista.__str__( ) + """ }]}; var lineOptions = {responsive: true};var ctx = document.getElementById("lineChart").getContext("2d");new Chart(ctx, {type: 'line', data: lineData, options:lineOptions}); });</script> """ res = res + "</body></html>" #return HttpResponseRedirect("/") return HttpResponse(res)
def solution(pars): (a2,a1,a0),(t1,t2),(k1,k2),(y0,yd0)=pars a2,a1,a0 = map(int,[a2,a1,a0]) den = a2*s**2+a1*s+a0 V1 = apart(1/s/den).as_ordered_terms() # const. V2 = apart(1/s**2/den).as_ordered_terms() # lin. Iv1,Iv2 = ilt_pfe(V1),ilt_pfe(V2) LIC = (a2*(s*y0+yd0) + a1*y0)/den y1 = ILT(LIC, s,t) y2 = k1*Iv2 # k1, t y3 = (k2-k1)*Iv2.subs(t,t-t1)*H(t-t1) # k2-k1,(t-t1)*H(t-t1) y4 = (t1*(k2-k1)-k2*t2)*Iv1.subs(t,t-t1)*H(t-t1) # t1*(k2-k1)-k2*t2,H(t-t1), nulove pre spojite y5 = -k2*Iv2.subs(t,t-t2)*H(t-t2) # -k2, (t-t2)*H(t-t2) y = expand_mul(simplify(y1+y2+y3+y4+y5)) return y
def expand(expression, variable=None): expression = expand_(expression) if isinstance(expression, Basic) and expression.is_rational_function(): if variable is None: variable = extract_var(expression) return apart(expression, variable) return expression
def apart(arg,substituteFloats=False,**kw): r"""Performs apart operation on arg. Symbolic variables are left symbolic, but variables with values are treated as the values (!) :param Variable|Operation|Expression arg: argument to be processed :param bool substituteFloats: non-symbolic variables are treated as their float values if True, they are left otherwise :param \*\*kw: keywords for sympy.apart() function :rtype: type(arg) .. code-block:: python >>> import latexexpr.sympy as lsympy >>> x = latexexpr.Variable('x',None) >>> e1 = latexexpr.Expression('e1', (4*x**3 + 21*x**2 + 10*x + 12) / (x**4 + 5*x**3 + 5*x**2 + 4*x) ) >>> print lsympy.apart(e1) e1 = \frac{ {1} }{ {1} + {x} + { {x} }^{ {2} } } \cdot \left( {-1} + {2} \cdot {x} \right) + \left( - \frac{ {1} }{ {4} + {x} } \right) + {3} \cdot \frac{ {1} }{ {x} } """ if isinstance(arg,latexexpr.Variable): return arg if isinstance(arg,latexexpr.Expression): ret = copy.copy(arg) ret.apart(substituteFloats,**kw) return ret if isinstance(arg,latexexpr.Operation): s,lVars = _operation2sympy(arg,substituteFloats=substituteFloats) s = sympy.apart(s,**kw) return _sympy2operation(s,lVars) raise TypeError, "Unsupported type (%s) for apart"%(arg.__class__.__name__)
def expand(expression, variable = None): expression = expand_(expression) if isinstance(expression, Basic) and expression.is_rational_function(): if variable is None: variable = extract_var(expression) return apart(expression, variable) return expression
def apply(self, expr, var, evaluation): 'Apart[expr_, var_Symbol]' expr_sympy = expr.to_sympy() var_sympy = var.to_sympy() result = sympy.apart(expr_sympy, var_sympy) result = from_sympy(result) return result
def zoh_discretization(t, k, s, z, T, P): pfe = sp.apart(P / s) terms = pfe.args if isinstance(pfe, sp.Add) else [pfe] terms = [ sp.inverse_laplace_transform(term, s, t).subs(t, k * T) for term in terms ] terms = [term.subs(sp.Heaviside(T * k), 1) for term in terms] return (z - 1) / z * z_transform(k, z, sum(terms))
def Apart(formula): try: x = Symbol('x') anser = apart(formula) anser = LATEX(formula) + "=" + LATEX(anser) except: anser = "Error" flash("エラー:もう一度入力してください") return anser
def ctrl_ilt(expr): ilt = 0 expanded = sym.apart(expr).as_ordered_terms() print('Expanded this is ', expanded) for term in expanded: print('Terms are ', term) print(sym.inverse_laplace_transform(term, s, t)) ilt += sym.inverse_laplace_transform(term, s, t) return ilt
def expand(expression, variable = None): expression = expand_(expression) if isinstance(expression, Basic) and expression.is_rational_function(): # Éviter d'appeler `apart()` pour rien, d'autant que FloatFrac() n'est # pas compatible avec apart() (sympy v0.7.2). num, den = expression.as_numer_denom() if den.free_symbols: if variable is None: variable = extract_var(expression) return apart(expression, variable) return expression
def eval(self, e): if isinstance(e, str): e = parser.parse_expr(e) if e.ty == OP and e.op != "/" and not (e.ty == OP and e.op == "*" and e.args[1].ty == OP and e.args[1].op == "^"\ and (e.args[1].args[1].ty == OP and len(e.args[1].args[1]) == 1 or e.args[1].args[1].ty == CONST and e.args[1].args[1].val < 0)): return e result = apart(expr.sympy_style(e)) return parser.parse_expr(str(result).replace("**","^"))
def apply(self, expr, var, evaluation): 'Apart[expr_, var_Symbol]' expr_sympy = expr.to_sympy() var_sympy = var.to_sympy() try: result = sympy.apart(expr_sympy, var_sympy) result = from_sympy(result) return result except sympy.PolynomialError: # raised e.g. for apart(sin(1/(x**2-y**2))) return expr
def __init__(self): self.num_lines, self.num_marks = 7, 3 self._qp = {} self._qp['function_type'] = random.choice( ['exp', 'hyperbola', 'log', 'cubic']) if self._qp['function_type'] == 'exp': func = all_functions.request_exp(difficulty=3) self._qp['domain'], self._qp['range'] = func.domain, func.range self._qp['equation'] = func.equation self._qp['inverse'] = simplify.canonise_log( all_functions.inverse(self._qp['equation'])) elif self._qp['function_type'] == 'hyperbola': func = all_functions.request_hyperbola(difficulty=3) self._qp['domain'], self._qp['range'] = func.domain, func.range self._qp['equation'] = func.equation self._qp['inverse'] = sympy.apart( all_functions.inverse(self._qp['equation'])) elif self._qp['function_type'] == 'log': func = all_functions.request_log(difficulty=3) self._qp['domain'], self._qp['range'] = func.domain, func.range self._qp['equation'] = func.equation self._qp['inverse'] = all_functions.inverse(self._qp['equation']) elif self._qp[ 'function_type'] == 'cubic': # no base class for cubics so I make it here m = not_named_yet.randint_no_zero(-3, 3) c = not_named_yet.randint_no_zero(-5, 5) self._qp['equation'] = m * x**3 + c self._qp['inverse'] = all_functions.inverse(self._qp['equation']) if random.choice([True, False]): self._qp['domain'] = sympy.Interval(-sympy.oo, 0) if m > 0: self._qp['range'] = sympy.Interval(-sympy.oo, c) else: self._qp['range'] = sympy.Interval(c, sympy.oo) else: self._qp['domain'] = sympy.Interval(0, sympy.oo) if m > 0: self._qp['range'] = sympy.Interval(c, sympy.oo) else: self._qp['range'] = sympy.Interval(-sympy.oo, c) self._qp['inverse_domain'] = self._qp['range']
def handle_apart(message): try: message.text = rstr(message) if (len(message.text) != 0): s = apart(message.text) lat = sympy.printing.latex(s) plt.text(0, 0.3, r"$%s$" % lat, fontsize=30) plt.axis('off') plt.savefig('plot.png') photo = open('plot.png', 'rb') bot.send_photo(message.chat.id, photo, s) plt.close() except BaseException: bot.send_message(message.chat.id, 'Ошибка при вводе дроби!')
def test_action_verbs(): assert nsimplify((1/(exp(3*pi*x/5)+1))) == (1/(exp(3*pi*x/5)+1)).nsimplify() assert ratsimp(1/x + 1/y) == (1/x + 1/y).ratsimp() assert trigsimp(log(x), deep=True) == (log(x)).trigsimp(deep = True) assert radsimp(1/(2+sqrt(2))) == (1/(2+sqrt(2))).radsimp() assert powsimp(x**y*x**z*y**z, combine='all') == (x**y*x**z*y**z).powsimp(combine='all') assert simplify(x**y*x**z*y**z) == (x**y*x**z*y**z).simplify() assert together(1/x + 1/y) == (1/x + 1/y).together() assert separate((x*(y*z)**3)**2) == ((x*(y*z)**3)**2).separate() assert collect(a*x**2 + b*x**2 + a*x - b*x + c, x) == (a*x**2 + b*x**2 + a*x - b*x + c).collect(x) assert apart(y/(y+2)/(y+1), y) == (y/(y+2)/(y+1)).apart(y) assert combsimp(y/(x+2)/(x+1)) == (y/(x+2)/(x+1)).combsimp() assert factor(x**2+5*x+6) == (x**2+5*x+6).factor() assert refine(sqrt(x**2)) == sqrt(x**2).refine() assert cancel((x**2+5*x+6)/(x+2)) == ((x**2+5*x+6)/(x+2)).cancel()
def __init__(self): self.num_lines, self.num_marks = 7, 3 self._qp = {} self._qp['function_type'] = random.choice(['exp', 'hyperbola', 'log', 'cubic']) if self._qp['function_type'] == 'exp': func = all_functions.request_exp(difficulty=3) self._qp['domain'], self._qp['range'] = func.domain, func.range self._qp['equation'] = func.equation self._qp['inverse'] = simplify.canonise_log(all_functions.inverse(self._qp['equation'])) elif self._qp['function_type'] == 'hyperbola': func = all_functions.request_hyperbola(difficulty=3) self._qp['domain'], self._qp['range'] = func.domain, func.range self._qp['equation'] = func.equation self._qp['inverse'] = sympy.apart(all_functions.inverse(self._qp['equation'])) elif self._qp['function_type'] == 'log': func = all_functions.request_log(difficulty=3) self._qp['domain'], self._qp['range'] = func.domain, func.range self._qp['equation'] = func.equation self._qp['inverse'] = all_functions.inverse(self._qp['equation']) elif self._qp['function_type'] == 'cubic': # no base class for cubics so I make it here m = not_named_yet.randint_no_zero(-3, 3) c = not_named_yet.randint_no_zero(-5, 5) self._qp['equation'] = m * x ** 3 + c self._qp['inverse'] = all_functions.inverse(self._qp['equation']) if random.choice([True, False]): self._qp['domain'] = sympy.Interval(-sympy.oo, 0) if m > 0: self._qp['range'] = sympy.Interval(-sympy.oo, c) else: self._qp['range'] = sympy.Interval(c, sympy.oo) else: self._qp['domain'] = sympy.Interval(0, sympy.oo) if m > 0: self._qp['range'] = sympy.Interval(c, sympy.oo) else: self._qp['range'] = sympy.Interval(-sympy.oo, c) self._qp['inverse_domain'] = self._qp['range']
def handle_apart(message): try: message.text = str(message) if (len(message.text) != 0): init_printing() s = simplify(message.text) lat = sympy.latex(s) plt.text(0, 0.6, r"$%s$" % s, fontsize=50) plt.axis('off') plt.savefig('plot.png') bot.send_message(message.chat.id, apart(message.text)) photo = open('plot.png', 'rb') bot.send_photo(message.chat.id, photo) plt.close() except BaseException: bot.send_message(message.chat.id, 'Ошибка при вводе дроби!')
def given(): a, b, c, d, e, f = random.sample(range(-9, -1) + range(1, 9), 6) #x = a/b rs = a - c ls = b * x - c rs = d * rs / ls ls = 1 - e * x / (d + e * x) rs = rs / (d + e * x) rs = apart(rs) ls = ls / f rs = rs / f ls1, ls2 = ls.as_two_terms() rs1, rs2 = rs.as_two_terms() g = Struct() g.sls = sstr(S(ls1) + S(ls2)) g.srs = sstr(S(rs1) + S(rs2)) return g
def _make_T_denom_sym(self, ): r''' A method to prepare the symbolic expression T_denom_sym for further computations. This expression represents the denominator in terms of a symbol x, which represents the shortest time delay in the network. ''' self._make_decimal_delays() self.x = sp.symbols('x') E_sym = sp.Matrix(np.zeros_like(self.M1)) for i, delay in enumerate(self.Decimal_delays): E_sym[i, i] = self.x**int(delay / self.Decimal_gcd) M1_sym = sp.Matrix(self.M1) self.T_denom_sym = sp.apart((E_sym - M1_sym).det()) ## I use apart above because sympy yields a function that is not ## completely reduced. Alternatively, can use *.as_numer_denom() ## and take the first component for the numerator. However, this could ## results in spurious roots if the denominator is nontrivial. return
def _make_T_denom_sym(self,): r''' A method to prepare the symbolic expression T_denom_sym for further computations. This expression represents the denominator in terms of a symbol x, which represents the shortest time delay in the network. ''' self._make_decimal_delays() self.x = sp.symbols('x') E_sym = sp.Matrix(np.zeros_like(self.M1)) for i,delay in enumerate(self.Decimal_delays): E_sym[i,i] = self.x**int(delay / self.Decimal_gcd) M1_sym = sp.Matrix(self.M1) self.T_denom_sym = sp.apart((E_sym - M1_sym).det()) ## I use apart above because sympy yields a function that is not ## completely reduced. Alternatively, can use *.as_numer_denom() ## and take the first component for the numerator. However, this could ## results in spurious roots if the denominator is nontrivial. return
L_ode_4 # In[74]: Y_sol = sympy.solve(L_ode_4, Y) # In[75]: Y_sol # In[76]: sympy.apart(Y_sol[0]) # In[77]: y_sol = sympy.inverse_laplace_transform(Y_sol[0], s, t) # In[78]: sympy.simplify(y_sol) # In[79]: y_t = sympy.lambdify(t, y_sol, 'numpy')
from sympy import together, apart, symbols from sympy import * x1, x2, x3, x4 = symbols('x1 x2 x3 x4') x1/x2 + x3/x4 together(x1/x2 + x3/x4) apart ((2*x**2+3*x+4)/(x+1)) together(apart ((2*x**2+3*x+4)/(x+1))) log(4).n() log(4,4).n() ln(4).n() mpmath.log10(4)
def apart_fact(Fs): S=0 Ls = apart(Fs).as_ordered_terms() for l in Ls: S += numer(l)/factor(denom(l)) return expand_mul(S)
def test_H31(): f = (x**2 + 2 * x + 3) / (x**3 + 4 * x**2 + 5 * x + 2) g = 2 / (x + 1)**2 - 2 / (x + 1) + 3 / (x + 2) assert apart(f) == g
if isinstance(e, (sympy.Add, sympy.Mul)): t = type(e) return t(*[laplace_transform_derivatives(arg) for arg in e.args]) return e L_ode_2 = laplace_transform_derivatives(L_ode) print(L_ode_2) L_ode_3 = L_ode_2.subs(L_y, Y) print(L_ode_3) ics = {y(0): 1, y(t).diff(t).subs(t, 0): 0} print(ics) L_ode_4 = L_ode_3.subs(ics) print(L_ode_4) Y_sol = sympy.solve(L_ode_4, Y) print(Y_sol) sympy.apart(Y_sol[0]) y_sol = sympy.inverse_laplace_transform(Y_sol[0], s, t) sympy.simplify(y_sol) y_t = sympy.lambdify(t, y_sol, 'numpy') fig, ax = plt.subplots(figsize=(8, 4)) tt = np.linspace(0, 10, 500) ax.plot(tt, y_t(tt).real) ax.set_xlabel(r"$t$", fontsize=18) ax.set_ylabel(r"$y(t)$", fontsize=18) fig.tight_layout() os.system("pause")
def explanation(pars,for_tex=False): (a2,a1,a0),(t1,t2),(k1,k2),(y0,yd0)=pars a2,a1,a0 = map(int,[a2,a1,a0]) Chpol = a2*s**2+a1*s+a0 r12 = solve(Chpol,s) if len(r12)==2: r1,r2=r12 else: r1=r12[0]; r2=r1 # nezavisle od parametrov realroots = (complex(r1).imag == 0) kps = t1*(k2-k1)-k2*t2 continuous = (kps == 0) if not for_tex: beg_eqn = r"$$\begin{eqnarray*}" end_eqn = r"\end{eqnarray*}$$" else: beg_eqn = r"\begin{eqnarray*}" end_eqn = r"\end{eqnarray*}" Lls = Chpol * Y(s) IC = a1*y0+s*y0+yd0 ict = IC/Chpol y0t = simplify(ILT(ict,s,t)) if realroots: y0t = H(t)*expand_mul(simplify(y0t/H(t))) if not continuous: V1 = apart(1/s/Chpol).as_ordered_terms() Iv1 = ilt_pfe(V1) y1t = expand_mul(simplify(Iv1/H(t))) V2 = apart(1/s**2/Chpol).as_ordered_terms(); Iv2 = ilt_pfe(V2) y2t = expand_mul(simplify(Iv2/H(t))) if realroots: icpfe=latex(apart_fact(ict)) else: icpfe=latex(ict) if not continuous: Ykstr=r"""%s Y_0(s) &=& %s,\\ Y_1(s) &=& \frac{1}{s (%s)},\\ Y_2(s) &=& \frac{1}{s^2 (%s)}.\\ %s""" %(beg_eqn,latex(ict),latex(Chpol),latex(Chpol),end_eqn) ytstr=r"""%s y_0(t) &=& %s,\\ y_1(t) &=& \theta(t) \left({%s}\right),\\ y_2(t) &=& \theta(t) \left({%s}\right).\\ %s""" %(beg_eqn,latex(y0t,fold_func_brackets=True), latex(y1t,fold_func_brackets=True), latex(y2t,fold_func_brackets=True),end_eqn) pfestr=r"""%s Y_0(s) &=& %s,\\ Y_1(s) &=& %s,\\ Y_2(s) &=& %s.\\ %s""" %(beg_eqn,icpfe,latex(apart(1/s/Chpol)),latex(apart(1/s**2/Chpol)),end_eqn) else: Ykstr=r"$$Y_0(s) = %s,\ Y_1(s) = \frac{1}{s^2 (%s)}.$$" %(latex(ict),latex(Chpol)) ytstr=r"""%s y_0(t) &=& %s,\\ y_1(t) &=& \theta(t) \left({%s}\right).\\ %s""" %(beg_eqn,latex(y0t,fold_func_brackets=True), latex(y2t,fold_func_brackets=True),end_eqn) pfestr=r"$$Y_0(s) =%s,\ Y_1(s) = %s.$$" %(icpfe,latex(apart_fact(1/s**2/Chpol))) ic1,ic2 = s*Y(s)- y0, s**2*Y(s) - y0*s - yd0 f = k1*t*(H(t)-H(t-t1))+k2*(t-t2)*(H(t-t1)-H(t-t2)) ct1,ct2=factor((k2-k1)*(t-t1)),factor(-k2*(t-t2)) fh =k1*t*H(t)+ct1*H(t-t1)+ct2*H(t-t2) if not continuous: fh = fh + kps*H(t-t1) Lfh = expand_mul(LT(fh,t,s)[0]) y2t1 = y2t.subs(t,t-t1); y2t2 = y2t.subs(t,t-t2) if not continuous: y1t1 = y1t.subs(t,t-t1) yt = y0t + k1*y2t + (k2-k1)*y2t1*H(t-t1) - k2*y2t2*H(t-t2) if not continuous: yt = yt + kps*y1t1*H(t-t1) yder = diff(y0t/H(t),t)*H(t) + k1*diff(y2t,t)*H(t)+(k2-k1)*diff(y2t1,t)*H(t-t1)-k2*diff(y2t2,t)*H(t-t2) if not continuous: yder = yder + kps*diff(y1t1,t)*H(t-t1) yder2 = diff(y0t/H(t),t,2)*H(t) + k1*diff(y2t,t,2)*H(t)+(k2-k1)*diff(y2t1,t,2)*H(t-t1)-k2*diff(y2t2,t,2)*H(t-t2) if not continuous: yder2 = yder2 + kps*diff(y1t1,t,2)*H(t-t1) if continuous: sol2 = latex(k1 * y1(t) + (k2-k1)*y1(t-t1) - k2 * y1(t-t2)) else: sol2 = latex(k1 * y2(t) + (k2-k1)*y2(t-t1) - k2 * y2(t-t2) + kps*y1(t-t1)) sol2 = sol2.replace('\\operatorname','') if kps < 0: SolStr = "y(t) = y_0(t) " + sol2 else: SolStr = "y(t) = y_0(t) + " + sol2 Fcheck=a2*yder2+a1*yder+a0*yt Is_solution=simplify(Fcheck-f) Estr=[r"""Nech $y(t) \rightarrow Y(s)$. Pre transformáciu ľavej strany použijeme vzorce: %s y'(t) &\rightarrow & s Y(s)- y(0)=%s,\\ y''(t) &\rightarrow & s^2 Y(s) - s y(0) -y'(0)= %s.\\ %s""" %(beg_eqn,latex(ic1), latex(ic2),end_eqn), r"""Pravú stranu prepíšeme pomocou Heavisideovho skoku $\theta(t)\,$ takto: $$f(t)=%s.$$ Keď chceme mať rovnaké posunutia vo funkcii aj v Heavisidovom skoku, upravíme to $$f(t)=%s.$$ Je to treba kvôli použitiu pravidla o posunutí originálu $$\mbox{ ak } f(t) \rightarrow F(s), \mbox{ potom } f(t-a) \rightarrow \mathrm{e}^{-a s} F(s),$$ pre transformáciu pravej strany. Teraz môžeme napísať L-transformovanú rovnicu (nezlomkové členy vznikli z počiatočných podmienok, ktoré sme zahrnuli do pravej strany): $$%s = %s.$$ """ %(latex(f),latex(fh),latex(Lls),latex(Lfh +a1*y0 +s* y0 + yd0)), r"""Korene charakteristickej rovnice sú $r_1=%s,\, r_2=%s.$ Vzhľadom na horeuvedené pravidlo o posunutí originálu a linearitu L-transformácie stačí hľadať originály len pre výrazy %s Urobili by sme to rozkladom na elementárne zlomky, ale robotu nám ušetrí softvér ($\textit{sympy}$) a dostaneme %s Pre originály máme %s Nakoniec, použitím pravidla o posunutí a linearity L-transformácie dostaneme celkové riešenie $$%s.$$ Pomocou $\textit{sympy}$ overíme, či je to riešenie. Je, lebo rozdiel ľavej a pravej strany je $%s$. """ %(latex(r1),latex(r2),Ykstr, pfestr, ytstr, SolStr, latex(Is_solution)) ] return Estr[0]+Estr[1]+Estr[2], t1, t2, f, yt, yder, yder2
def test_H31(): f = (x**2 + 2*x + 3)/(x**3 + 4*x**2 + 5*x + 2) g = 2 / (x + 1)**2 - 2 / (x + 1) + 3 / (x + 2) assert apart(f) == g
def __init__(self): self.s, self.t, self.x, self.y, self.z = symbols('s,t,x,y,z') self.stack = [] self.defs = {} self.mode = 0 self.hist = [('', [])] # Innehåller en lista med (kommandorad, stack) self.lastx = '' self.clear = True self.op0 = { 's': lambda: self.s, 't': lambda: self.t, 'x': lambda: self.x, 'y': lambda: self.y, 'z': lambda: self.z, 'oo': lambda: S('oo'), 'inf': lambda: S('oo'), 'infinity': lambda: S('oo'), '?': lambda: self.help(), 'help': lambda: self.help(), 'hist': lambda: self.history(), 'history': lambda: self.history(), 'sketch': lambda: self.sketch(), } self.op1 = { 'radians': lambda x: pi / 180 * x, 'sin': lambda x: sin(x), 'cos': lambda x: cos(x), 'tan': lambda x: tan(x), 'sq': lambda x: x**2, 'sqrt': lambda x: sqrt(x), 'ln': lambda x: ln(x), 'exp': lambda x: exp(x), 'log': lambda x: log(x), 'simplify': lambda x: simplify(x), 'polynom': lambda x: self.polynom(x), 'inv': lambda x: 1 / x, 'chs': lambda x: -x, 'center': lambda x: x.center, 'radius': lambda x: x.radius, 'expand': lambda x: x.expand(), 'factor': lambda x: x.factor(), 'incircle': lambda x: x.incircle, 'circumcircle': lambda x: x.circumcircle, 'xdiff': lambda x: x.diff(self.x), 'ydiff': lambda x: x.diff(self.y), 'xint': lambda x: x.integrate(self.x), 'xsolve': lambda x: solve(x, self.x), 'xapart': lambda x: apart(x, self.x), 'xtogether': lambda x: together(x, self.x), 'N': lambda x: N(x), 'info': lambda x: [x.__class__.__name__, [m for m in dir(x) if m[0] != '_']], } self.op2 = { '+': lambda x, y: y + x, '-': lambda x, y: y - x, '*': lambda x, y: y * x, '/': lambda x, y: y / x, '**': lambda x, y: y**x, 'item': lambda x, y: y[x], 'point': lambda x, y: Point(y, x), 'line': lambda x, y: Line(y, x), 'circle': lambda x, y: Circle(y, x), 'tangent_lines': lambda x, y: y.tangent_lines(x), 'intersection': lambda x, y: intersection(x, y), 'perpendicular_line': lambda x, y: y.perpendicular_line(x), 'diff': lambda x, y: y.diff(x), 'int': lambda x, y: y.integrate(x), 'solve': lambda x, y: solve(y, x), 'apart': lambda x, y: apart(y, x), 'together': lambda x, y: together(y, x), 'xeval': lambda x, y: y.subs(self.x, x), } self.op3 = { 'triangle': lambda x, y, z: Triangle(x, y, z), 'limit': lambda x, y, z: limit( z, y, x), # limit(sin(x)/x,x,0) <=> x sin x / x 0 limit 'eval': lambda x, y, z: z.subs(y, x), } self.op4 = { 'sum': lambda x, y, z, t: Sum(t, (z, y, x)).doit( ) # Sum(1/x**2,(x,1,oo)).doit() <=> 1 x x * / x 1 oo sum } self.lastx = ''
def partial_decomp(expression): ''' sympy.apart() will do partial fraction decomposition on a rational function ''' return apart(expression)
expr.collect(y) # In[92]: expr = sympy.cos(x + y) + sympy.sin(x - y) # In[93]: expr.expand(trig=True).collect([sympy.cos(x), sympy.sin(x) ]).collect(sympy.cos(y) - sympy.sin(y)) # ### Together, apart, cancel # In[94]: sympy.apart(1 / (x**2 + 3 * x + 2), x) # In[95]: sympy.together(1 / (y * x + y) + 1 / (1 + x)) # In[96]: sympy.cancel(y / (y * x + y)) # ### Substitutions # In[97]: (x + y).subs(x, y)
print(scale) print("factored:") scale = sympy.factor(scale) print(scale) scale = scale.subs(L, sympy.sympify("8/10")) scale = scale.subs(sigma, sympy.sympify("50/1000000")) scale = scale.subs(a, sympy.sympify("4/1000")) scale = scale.subs(epsilon, 1) scale = scale.subs(M, 1) #scale = scale.subs(M,1e-6) scale = scale.subs(dA, 1) print("partial fraction decomposition:") scale = sympy.apart(scale) print(scale) print("simplify") #sigmak2 = var[0,0] #sigmak2 = var[1,1] #sigmak2 = 2*var[1,2]/k #sigmak2 = 4*var[2,2]/k**2 sigmak2 = 4 * var #sigmak2 = varinv #sigmak2 = var.det() #sigmak2 = var[1,1] + var[2,2] - 2*var[1,2] #sigmak2 = 4*var #sigmak2 = var.diagonalize(sort=True)[1] #sigmak2 = varinv.adjugate() #sigmak2 = varinv
# F(s) = s + 1 / s^2 (s+2) import sympy s = sympy.symbols('s') f = (s + 1) / ((s**2) * (s + 2)) print(sympy.apart(f))
import sympy as sp sp.init_printing() s = sp.Symbol('s') t = sp.Symbol('t', positive=True) w = sp.Symbol('w', real=True) p1 = sp.Symbol('p1', real=True) p2 = sp.Symbol('p2', real=True) P = sp.apart(w**2 / (s * (s - p1) * (s - p2)), s) print(sp.inverse_laplace_transform(P, s, t))
print("b=", B) print("a=", A) i = 0 for j in A: print('.param A' + repr(4 - i) + '=', A[i]) i = i + 1 i = 0 for j in B: print('.param B' + repr(2 - i) + '=', B[i]) i = i + 1 #%% Partial Fract import sympy as sp from sympy import latex from IPython.display import display, Latex sp.init_printing(use_latex='mathjax') result = lambda fun: "$${}$$".format(latex(fun)) s = sp.symbols("s") display('s') #%% num = (B[0] * s**2 + B[1] * s + B[2]) den = (A[0] * s**2 + A[1] * s + A[2]) # den = (s + np.roots(A)[0] )* (s+np.roots(A)[1]) display(Latex(result(num / den))) decomp = sp.apart(num / (den), full=True) display(Latex(result((decomp.doit())))) #%% #%%
def step_response_numerical_data(system, prec=8, lower_limit=0, upper_limit=10, **kwargs): """ Returns the numerical values of the points in the step response plot of a SISO continuous-time system. By default, adaptive sampling is used. If the user wants to instead get an uniformly sampled response, then ``adaptive`` kwarg should be passed ``False`` and ``nb_of_points`` must be passed as additional kwargs. Refer to the parameters of class :class:`sympy.plotting.plot.LineOver1DRangeSeries` for more details. Parameters ========== system : SISOLinearTimeInvariant The system for which the unit step response data is to be computed. prec : int, optional The decimal point precision for the point coordinate values. Defaults to 8. lower_limit : Number, optional The lower limit of the plot range. Defaults to 0. upper_limit : Number, optional The upper limit of the plot range. Defaults to 10. kwargs : Additional keyword arguments are passed to the underlying :class:`sympy.plotting.plot.LineOver1DRangeSeries` class. Returns ======= tuple : (x, y) x = Time-axis values of the points in the step response. NumPy array. y = Amplitude-axis values of the points in the step response. NumPy array. Raises ====== NotImplementedError When a SISO LTI system is not passed. When time delay terms are present in the system. ValueError When more than one free symbol is present in the system. The only variable in the transfer function should be the variable of the Laplace transform. When ``lower_limit`` parameter is less than 0. Examples ======== >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction >>> from sympy.physics.control.control_plots import step_response_numerical_data >>> tf1 = TransferFunction(s, s**2 + 5*s + 8, s) >>> step_response_numerical_data(tf1) # doctest: +SKIP ([0.0, 0.025413462339411542, 0.0484508722725343, ... , 9.670250533855183, 9.844291913708725, 10.0], [0.0, 0.023844582399907256, 0.042894276802320226, ..., 6.828770759094287e-12, 6.456457160755703e-12]) See Also ======== step_response_plot """ if lower_limit < 0: raise ValueError("Lower limit of time must be greater " "than or equal to zero.") _check_system(system) _x = Dummy("x") expr = system.to_expr() / (system.var) expr = apart(expr, system.var, full=True) _y = _fast_inverse_laplace(expr, system.var, _x).evalf(prec) return LineOver1DRangeSeries(_y, (_x, lower_limit, upper_limit), **kwargs).get_points()
from __future__ import division, print_function from sympy import S, apart, summation k = S('k') k_domain = (k, 1, 00) f_Y = 18/((k+1)*(k+2)*(k+3)) print( " = ".join([ f_Y, apart(f_Y) ]) ) EY = summation( f_Y, k_domain ) print( "E[Y] = {}".format( EY ) )
def answer_to_user(message): print('%s (%s): %s' %(message.chat.first_name, message.chat.username, message.text)) msg = None if message.text.lower() == 'помощь': msg = bot.send_message(message.chat.id, HELP_MESSAGE, parse_mode='markdown') elif re.search('квур -?\d+ -?\d+ -?\d+', message.text.lower()): str1 = message.text.lower() result = re.findall(r'-?\d+', str1) print(result) try: a,b,c = map(float, result) discr = (b * b) - 4 * a * c if discr > 0: x1 = (-b + math.sqrt(discr)) / (2 * a) x2 = (-b - math.sqrt(discr)) / (2 * a) msg = "x1 = " + str(x1) + " x2 = " + str(x2) bot.send_message(message.chat.id, msg) elif discr == 0: x = -b / (2 * a) bot.send_message(message.chat.id, "x = " + str(x)) else: bot.send_message(message.chat.id, "Корней нет.(D < 0)") except: bot.send_message(message.chat.id, "Что-то не так.Проверьте вводимые данные или напишите /help для помощи.") elif re.search('зн -?[0-9?a-z?A-Z?]', message.text.lower()): str1 = message.text.lower() try: result = re.sub(r"зн", "", str1, count=0) init_printing(use_unicode=False, wrap_line=False, no_global=True) from sympy import Symbol x = Symbol('x') y = Symbol('y') result1 = together(apart(result, x), x) bot.send_message(message.chat.id, result1) except: bot.send_message(message.chat.id, "Что-то не так.Проверьте вводимые данные или напишите /help для помощи.") elif re.search('предел -?[0-9?a-z?A-Z?]', message.text.lower()): str1 = message.text.lower() try: result1 = re.sub(r"предел", "", str1, count=0) bot.send_message(message.chat.id, "Вы ввели " + result1 + ". Вычисление...") lst = result1.split() from sympy import Symbol user_func = lst[0] seek = lst[1] x = Symbol("x") y = Symbol("y") from sympy import limit result = limit(user_func, x, seek) bot.send_message(message.chat.id, result) except: bot.send_message(message.chat.id, "Что-то не так.Проверьте вводимые данные или напишите /help для помощи.") elif re.search('диф -?[0-9?a-z?A-Z?]', message.text.lower()): str1 = message.text.lower() result1 = re.sub(r"диф", "", str1, count=0) try: lst = result1.split() from sympy import Symbol x = Symbol('x') user_func1 = lst[0] order = lst[1] from sympy import diff res = 'Производная ' + order + '-ого порядка равна: ' result = diff(user_func1, x, order) bot.send_message(message.chat.id, res + str(result)) except: bot.send_message(message.chat.id, "Напишите /help для помощи.") elif re.search('опинт -?[0-9?a-z?A-Z?]', message.text.lower()): str1 = message.text.lower() try: result1 = re.sub(r"опинт", "", str1, count=0) lst = result1.split() from sympy import Symbol init_printing(use_unicode=False, wrap_line=False, no_global=True) x = Symbol('x') user_func3 = lst[0] a = lst[1] b = lst[2] from sympy import integrate result_2 = integrate(user_func3, (x, a, b)) bot.send_message(message.chat.id, result_2) except: bot.send_message(message.chat.id, "Напишите /help для помощи.") elif re.search('инт -?[0-9?a-z?A-Z?]', message.text.lower()): str1 = message.text.lower() try: result1 = re.sub(r"инт", "", str1, count=0) init_printing(use_unicode=False, wrap_line=False, no_global=True) from sympy import Symbol x = Symbol('x') user_func2 = result1 from sympy import integrate result_2 = integrate(user_func2, x) bot.send_message(message.chat.id, result_2) except: bot.send_message(message.chat.id, "Напишите /help для помощи.") try: answer = str(eval(message.text.lower().replace(' ', ''))) msg = bot.send_message(message.chat.id, message.text.lower().replace(' ', '') + ' = ' + answer) except SyntaxError: msg = bot.send_message(message.chat.id, 'Похоже, что вы написали что-то не так. \nИсравьте ошибку и повторите снова') except NameError: #msg = bot.send_message(message.chat.id, 'Переменную которую вы спрашиваете я не знаю. \nИсравьте ошибку и повторите снова') msg = 1 except TypeError: msg = bot.send_message(message.chat.id, 'Мне кажется, что в выражении присутствует ошибка типов. \nИсравьте ошибку и повторите снова') except ZeroDivisionError: msg = bot.send_message(message.chat.id, 'В выражении вы делите на ноль. \nИсравьте ошибку и повторите снова')
h = sy.Lambda(x, x**2) # h: x ↦ x² # h(5) = 25 # h(1+x): x ↦ (x+1)² # h(sy.sin(x)) x ↦ sin²(x) ## Expressions expr = 1 + 2 * x + 2 * x**2 # expr = 2x² + 2x + 1 print expr.args # (1, 2*x, 2*x**2) print expr.args[1].args[1] # x print expr.args[-1].args[1] # x**2 #### Voir Numerical Python Robert Johansson books polr = sy.apart(1 / (x**2 + 3 * x + 2), x) # Sort la décomposition en factions rationnelles den_com = sy.together(1 / (y * x + y) + 1 / (1 + x)) simplif = sy.cancel(y / (y * x + y)) x, y, z = sy.symbols("x, y, z", real=True) expr = x * y + z**2 * x values = {x: 1.25, y: 0.4, z: 3.2} print "{:.2f}".format(expr.subs(values)) ## Numerical evaluations # Use of sy.N #sy.N(np.pi + 2) print sy.N(np.pi + h(6)) #(36 + np.pi) expr = sy.sin(np.pi * x * sy.exp(x)) # N'est pas appelable expr_func = sy.lambdify(x, expr) # On l'a rendu appelable
print(e) r = solve(e, y)[0] print(r) print('SIMPLIFY') e = expand((x + 1) * (y + 1)) / (y + 1) print(e) e = simplify(e) print(e) print('TOGETHER, APART') e = 1 / x + 1 / y + 1 / z print(e) e = together(e) print(e) e = apart(e, x) print(e) print('COLLECT') e = y * x**2 + z * x - z * x**2 + z**2 * x + y**3 print(e) e = collect(e, x) print(e) e = expand(e) e = collect(e, z) print(e) print(latex(e)) print('PROBLEM_1') e1 = 2 * x + y + z - 1 e2 = x + 2 * y + z - 2
def impulse_response_numerical_data(system, prec=8, lower_limit=0, upper_limit=10, **kwargs): """ Returns the numerical values of the points in the impulse response plot of a SISO continuous-time system. By default, adaptive sampling is used. If the user wants to instead get an uniformly sampled response, then ``adaptive`` kwarg should be passed ``False`` and ``nb_of_points`` must be passed as additional kwargs. Refer to the parameters of class :class:`sympy.plotting.plot.LineOver1DRangeSeries` for more details. Parameters ========== system : SISOLinearTimeInvariant The system for which the impulse response data is to be computed. prec : int, optional The decimal point precision for the point coordinate values. Defaults to 8. lower_limit : Number, optional The lower limit of the plot range. Defaults to 0. upper_limit : Number, optional The upper limit of the plot range. Defaults to 10. kwargs : Additional keyword arguments are passed to the underlying :class:`sympy.plotting.plot.LineOver1DRangeSeries` class. Returns ======= tuple : (x, y) x = Time-axis values of the points in the impulse response. NumPy array. y = Amplitude-axis values of the points in the impulse response. NumPy array. Raises ====== NotImplementedError When a SISO LTI system is not passed. When time delay terms are present in the system. ValueError When more than one free symbol is present in the system. The only variable in the transfer function should be the variable of the Laplace transform. When ``lower_limit`` parameter is less than 0. Examples ======== >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction >>> from sympy.physics.control.control_plots import impulse_response_numerical_data >>> tf1 = TransferFunction(s, s**2 + 5*s + 8, s) >>> impulse_response_numerical_data(tf1) # doctest: +SKIP ([0.0, 0.06616480200395854,... , 9.854500743565858, 10.0], [0.9999999799999999, 0.7042848373025861,...,7.170748906965121e-13, -5.1901263495547205e-12]) See Also ======== impulse_response_plot """ if lower_limit < 0: raise ValueError("Lower limit of time must be greater " "than or equal to zero.") _check_system(system) _x = Dummy("x") expr = system.to_expr() expr = apart(expr, system.var, full=True) _y = _fast_inverse_laplace(expr, system.var, _x).evalf(prec) return LineOver1DRangeSeries(_y, (_x, lower_limit, upper_limit), **kwargs).get_points()
expr = x + y + x * y * z expr.collect(x) #%% expr.collect(y) #%% expr = sympy.cos(x + y) + sympy.sin(x - y) expr.expand(trig=True).collect([sympy.cos(x), sympy.sin(x) ]).collect(sympy.cos(y) - sympy.sin(y)) #%% md ### Apart, together, and cancel ### #%% sympy.apart(1 / (x**2 + 3 * x + 2), x) # rewrite expr as the partial fraction #%% sympy.together(1 / (y * x + 1) + 1 / (1 + x)) # combine the sum of fractions #%% sympy.cancel(y / (y * x + y)) # to cancel shared factor btw 분모,분자 #%% md ### Substitutions ### #%% (x + y).subs(x, y) #%% sympy.sin(x * sympy.exp(x)).subs(x, y)
# Result: 5/s**2 # Inverse Laplace transform (s->t) X = inverse_laplace_transform(U[0],s,t) print('X') print(X) # Result: 5*t*Heaviside(t) # Function F = 5*(s+1)/(s+3)**2 print('F') print(F) # Result: (5*s + 5)/(s + 3)**2 # Partial fraction decomposition G = sym.apart(F) print('G') print(G) # Result: 5/(s + 3) - 10/(s + 3)**2 # denominator of transfer function d1 = (s+1)*(s+3)*(s**2+3*s+1) # expand polynomial d2 = sym.expand(d1) print('d2') print(d2) # Result: s**4 + 7*s**3 + 16*s**2 + 13*s + 3 # find roots print(sym.roots(d2))
def ramp_response_numerical_data(system, slope=1, prec=8, lower_limit=0, upper_limit=10, **kwargs): """ Returns the numerical values of the points in the ramp response plot of a SISO continuous-time system. By default, adaptive sampling is used. If the user wants to instead get an uniformly sampled response, then ``adaptive`` kwarg should be passed ``False`` and ``nb_of_points`` must be passed as additional kwargs. Refer to the parameters of class :class:`sympy.plotting.plot.LineOver1DRangeSeries` for more details. Parameters ========== system : SISOLinearTimeInvariant The system for which the ramp response data is to be computed. slope : Number, optional The slope of the input ramp function. Defaults to 1. prec : int, optional The decimal point precision for the point coordinate values. Defaults to 8. lower_limit : Number, optional The lower limit of the plot range. Defaults to 0. upper_limit : Number, optional The upper limit of the plot range. Defaults to 10. kwargs : Additional keyword arguments are passed to the underlying :class:`sympy.plotting.plot.LineOver1DRangeSeries` class. Returns ======= tuple : (x, y) x = Time-axis values of the points in the ramp response plot. NumPy array. y = Amplitude-axis values of the points in the ramp response plot. NumPy array. Raises ====== NotImplementedError When a SISO LTI system is not passed. When time delay terms are present in the system. ValueError When more than one free symbol is present in the system. The only variable in the transfer function should be the variable of the Laplace transform. When ``lower_limit`` parameter is less than 0. When ``slope`` is negative. Examples ======== >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction >>> from sympy.physics.control.control_plots import ramp_response_numerical_data >>> tf1 = TransferFunction(s, s**2 + 5*s + 8, s) >>> ramp_response_numerical_data(tf1) # doctest: +SKIP (([0.0, 0.12166980856813935,..., 9.861246379582118, 10.0], [1.4504508011325967e-09, 0.006046440489058766,..., 0.12499999999568202, 0.12499999999661349])) See Also ======== ramp_response_plot """ if slope < 0: raise ValueError("Slope must be greater than or equal" " to zero.") if lower_limit < 0: raise ValueError("Lower limit of time must be greater " "than or equal to zero.") _check_system(system) _x = Dummy("x") expr = (slope * system.to_expr()) / ((system.var)**2) expr = apart(expr, system.var, full=True) _y = _fast_inverse_laplace(expr, system.var, _x).evalf(prec) return LineOver1DRangeSeries(_y, (_x, lower_limit, upper_limit), **kwargs).get_points()