def rational(eqn, numbers_to_test, debug=False): # Find rational zeros if isinstance(numbers_to_test, (int, float, Decimal)): numbers_to_test = [numbers_to_test] numbers_to_test = [Decimal(str(i)) for i in list(numbers_to_test)] if not isinstance(eqn, list): # Eqn is polynomial equation; extract coefficients eqn = toValidEqn(eqn) polynomial = Poly(sympify("Eq(" + eqn + ", 0)")) coeffs = [Decimal(str(i)) for i in polynomial.coeffs()] else: # Eqn is list of coefficients coeffs = [Decimal(str(i)) for i in eqn] positive_numbers_to_test = [ Decimal(str(abs(i))) for i in list(numbers_to_test) ] negative_numbers_to_test = [ Decimal(str(-abs(i))) for i in list(numbers_to_test) ] zeros = [] # Po for number in positive_numbers_to_test + negative_numbers_to_test: stack = number * coeffs[0] for i in range(1, len(coeffs)): stack += coeffs[i] stack *= number if debug == True: print(stack) if stack == 0: zeros.append(number) return '\n'.join([str(ans) for ans in zeros])
def main(): x = Symbol("x") s = Poly(A(x), x) num = list(reversed(s.coeffs()))[:11] print(s.as_expr()) print(num)
def get_algorithm_conditions(polynomials, steps): variables = set() for polynomial in polynomials: variables.update(polynomial.free_symbols) variables = list(variables) substitutions = [] step_results = [] conditions = [] for step in range(steps): left_multiplier = _make_multiplier("l_%d" % step, variables, step_results) right_multiplier = _make_multiplier("r_%d" % step, variables, step_results) step_result = symbols("s_{step}".format(step=step)) condition = (left_multiplier * right_multiplier).expand() substitutions.append([step_result, condition]) step_results.append(step_result) final_results = [] for i, polynomial in enumerate(polynomials): condition = _make_multiplier("f_%d" % i, variables, step_results) - polynomial for substitution in reversed(substitutions): condition = condition.subs(*substitution).expand() condition = condition.collect(variables) poly = Poly(condition, variables) conditions.extend(poly.coeffs()) #for condition in conditions: # print condition return conditions
def f_subs_R(re_eq=None, subs_im_d={}, qq_re=[], n=None, **kwargs): res_d = {} nn = qq_re[-1].derivative_count subs_d = f_generate_y_subs(n, A, limit=nn) subs_d_re = dict([[i, v] for i, v in subs_d.items() if i in qq_re]) subs_d_next = {diff(R(z), z, 1)**2: R(z)**2 * (1 - Xi * R(z)**2)} w0 = re_eq w0 = re_eq.subs(subs_im_d).doit() for i, v in subs_d_re.items(): w0 = w0.subs({i: v}).expand().simplify().doit() w1 = w0.subs(subs_d_next).doit() w2 = w1.expand().simplify().doit() h0 = Poly(w2, R(z)) r_coeffs = h0.coeffs() r_eqs = [Eq(i) for i in r_coeffs] res_d = { "nn": nn, "subs_d": subs_d, "subs_d_re": subs_d_re, "subs_d_next": subs_d_next, "w0": w0, "w1": w1, "w2": w2, "h0": h0, "r_coeffs": r_coeffs, "r_eqs": r_eqs } return res_d
def main(): x = Symbol("x") s = Poly(A(x), x) num = list(reversed(s.coeffs()))[:11] print s.as_basic() print num
def get_algorithm_conditions(polynomials, steps): assert (steps >= len(polynomials)) variables = set() for polynomial in polynomials: variables.update(polynomial.free_symbols) variables = list(variables) for operations in product(["+", "*"], repeat=steps): substitutions = [] conditions = [] step_results = [] for step, operation in enumerate(operations): computed_values = variables + step_results left_operand = _make_operand("l_%d" % step, computed_values, conditions) right_operand = _make_operand("r_%d" % step, computed_values, conditions) step_result = symbols("s_%d" % step) if operation == "*": rhs = (left_operand * right_operand).expand() elif operation == "+": rhs = left_operand + right_operand substitutions.append([step_result, rhs]) step_results.append(step_result) for polynomial, step_result in izip(polynomials, reversed(step_results)): condition = step_result - polynomial for substitution in reversed(substitutions): condition = condition.subs(*substitution).expand() condition = condition.collect(variables) poly = Poly(condition, variables) conditions.extend(poly.coeffs()) yield operations, conditions
def main(): x=Symbol("x") s = Poly(A(x), x) num = list(reversed(s.coeffs()))[:11] print s.as_basic() print num
def getAllLagranges(self): sym = Symbol('x') self.lagranges = [] for i in range(0, len(self.x), 1): l = self.getValueOfLagrange(self.x, i) lPoly = Poly(l, sym) cLpoly = self.getProberFormat(lPoly.coeffs()) self.lagranges.append("L" + str(i) + "(x)= " + str(Poly(cLpoly, sym))[5:-17])
def discrete_realization_tustin(n0, n1, d0, T): z = symbols('z') s = 2/T*(z-1)/(z+1) num = ((n1*s + n0)*T*(z + 1)).simplify() den = ((s + d0)*T*(z + 1)).simplify() num_poly = Poly(num, z) den_poly = Poly(den, z) n1_z, n0_z = num_poly.coeffs() d1_z, d0_z = den_poly.coeffs() # Make denominator monic and divide numerator appropriately n1_z /= d1_z n0_z /= d1_z d0_z /= d1_z a = -d0_z b_times_c = (n0_z - n1_z * d0_z).simplify() d = n1_z return a, b_times_c, d
def make_quadratic_eq(target, rhs=None, integer=[0, 1]): var = random.choice("pqrstuvwxyz") x = sympy.Symbol("x") f = random.randint(1, 5) * random.choice([-1, 1]) r1 = target while r1 == target: r1 = random.randint(1, 20) r2 = target - r1 expr = (f * x - r1 * f) * (x - r2) expanded_expr = expand(expr) print "I chose {}, {}, and {}".format(f, r1, r2) ex = Poly(expanded_expr, x) a, b, c = tuple(ex.coeffs()) print "I got {},{} and {}".format(a, b, c) out_str = "{}{}^2{}{}{}".format(a, var, right_sign(b), var, right_sign(c)) sols = sympy.latex(target) sols = "$$" + sols + "$$" out_str = "\\overline{" + out_str + "}" return out_str, sols
def _simpsol(soleq): lhs = soleq.lhs sol = soleq.rhs sol = powsimp(sol) gens = list(sol.atoms(exp)) p = Poly(sol, *gens, expand=False) gens = [factor_terms(g) for g in gens] if not gens: gens = p.gens syms = [Symbol('C1'), Symbol('C2')] terms = [] for coeff, monom in zip(p.coeffs(), p.monoms()): coeff = piecewise_fold(coeff) if type(coeff) is Piecewise: coeff = Piecewise(*((ratsimp(coef).collect(syms), cond) for coef, cond in coeff.args)) else: coeff = ratsimp(coeff).collect(syms) monom = Mul(*(g**i for g, i in zip(gens, monom))) terms.append(coeff * monom) return Eq(lhs, Add(*terms))
a, b, T, s, w, x, z, I = symbols('a b T s w x z I') bilinear_transform = {s: 2 / T * (z - 1) / (z + 1)} # Continuous time transfer function from I(s) to w(s) of the following plant # model: # dw/dt = a*w + b*I G_s = b / (s - a) G_z_num, G_z_den = G_s.subs(bilinear_transform).as_numer_denom() G_z_den = Poly(G_z_den, z) G_z_num = Poly(G_z_num / G_z_den.LC(), z) # divide by leading coefficient of den G_z_den = G_z_den.monic() # make denominator monic assert (G_z_den.coeffs()[0] == 1) kp = Poly(G_z_num.coeffs()[0], z) G_z_N_p = G_z_num - kp * G_z_den print(kp) print(G_z_N_p) print(G_z_den) from sympy import symbols, Poly import numpy as np a, b, T, s, w, x, z, I = symbols('a b T s w x z I') bilinear_transform = {s: 2 / T * (z - 1) / (z + 1)} # Continuous time transfer function from I(s) to w(s) of the following plant
yzz = diff(y(z), z, 2) #re_eq_ = a4 * yzzzz + (a2 - 6*a4*k**2 + 3*a3*k)*yzz + (a2*k**2 + 5*a4*k**4 + omega)*y(z) - b*y(z)**3 #w0 = re_eq_.subs(subs_im_d).doit() #w0 = re_eq_.subs({ a3 : 4 * a4 * k }).doit() for i, v in subs_d_re.items(): w0 = w0.subs({i: v}).expand().simplify().doit() #w0 = re_eq.subs(subs_d_re).doit() w1 = w0.subs(subs_d_next).doit() w2 = w1.expand().simplify().doit() h0 = Poly(w2, R(z)) r_coeffs = h0.coeffs() r_eqs = [Eq(i) for i in r_coeffs] #b_s = solve(r_eqs[0], b)[0] #a2_s = solve(r_eqs[1], a2)[0] #omega_s = solve(r_eqs[2], omega)[0] #subs_re_values = [ b_s, a2_s, omega_s ] #subs_re_keys = [ "b", "a2", "omega" ] #subs_re_d = dict(zip(map(eval, subs_re_keys), subs_re_values)) param_list = [b, a2, omega] eq_num_list = [0, 1, 2] subs_re_d = f_extract_from_eq_sys_(r_eqs, param_list, eq_num_list) #R_subs = A * 4 * a * exp(-alpha * z) / (4 * a**2 + Xi * exp(-2 * alpha * z))
# See equations 4.4.3 and 4.11.4 of Kane & Levinson Fr_c = Fr_u[:3, :].col_join(Fr_u[6:, :]) + A_rs.T * Fr_u[3:6, :] Fr_star_c = Fr_star_u[:3, :].col_join(Fr_star_u[6:, :])\ + A_rs.T * Fr_star_u[3:6, :] Fr_star_steady = Fr_star_c.subs(ud_zero).subs(u_dep_dict)\ .subs(steady_conditions).subs({q[3]: -r*cos(q[1])}).expand() mprint(Fr_c) mprint(Fr_star_steady) # First dynamic equation, under steady conditions is 2nd order polynomial in # dq0/dt. steady_turning_dynamic_equation = Fr_c[0] + Fr_star_steady[0] # Equilibrium is posible when the solution to this quadratic is real, i.e., # when the discriminant in the quadratic is non-negative p = Poly(steady_turning_dynamic_equation, qd[0]) a, b, c = p.coeffs() discriminant = b*b - 4*a*c # Must be non-negative for equilibrium # in case of thin disc inertia assumptions #mprint((discriminant / (r**3 * m**2)).expand()) # ADD ALL CODE DIRECTLY BELOW HERE, do not change above! # Think there should be at 12 assertion tests: # 1) Fr[i] == fr from KanesMethod i = 0, ..., 5 # 2) Fr_star[i] == frstar from KanesMethod i = 0, ..., 5 # if 2) is slow, try comparing this instead: # 2a) Fr_star_steady[i] == frstar from KanesMethod, evaluated at steady turning # conditions. # This should be something like frstar.subs(ud_zero).subs(steady_conditions)
# Form nonholonomic Fr and nonholonomic Fr_star # See equations 4.4.3 and 4.11.4 of Kane & Levinson Fr_c = Fr_u[:3, :].col_join(Fr_u[6:, :]) + A_rs.T * Fr_u[3:6, :] Fr_star_c = Fr_star_u[:3, :].col_join(Fr_star_u[6:, :])\ + A_rs.T * Fr_star_u[3:6, :] Fr_star_steady = Fr_star_c.subs(ud_zero).subs(u_dep_dict)\ .subs(steady_conditions).subs({q[3]: -r*cos(q[1])}).expand() mprint(Fr_c) mprint(Fr_star_steady) # First dynamic equation, under steady conditions is 2nd order polynomial in # dq0/dt. steady_turning_dynamic_equation = Fr_c[0] + Fr_star_steady[0] # Equilibrium is posible when the solution to this quadratic is real, i.e., # when the discriminant in the quadratic is non-negative p = Poly(steady_turning_dynamic_equation, qd[0]) a, b, c = p.coeffs() discriminant = b * b - 4 * a * c # Must be non-negative for equilibrium # in case of thin disc inertia assumptions #mprint((discriminant / (r**3 * m**2)).expand()) # ADD ALL CODE DIRECTLY BELOW HERE, do not change above! # Think there should be at 12 assertion tests: # 1) Fr[i] == fr from KanesMethod i = 0, ..., 5 # 2) Fr_star[i] == frstar from KanesMethod i = 0, ..., 5 # if 2) is slow, try comparing this instead: # 2a) Fr_star_steady[i] == frstar from KanesMethod, evaluated at steady turning # conditions. # This should be something like frstar.subs(ud_zero).subs(steady_conditions)
def sturm(): divid = [fx, diff(fx)] # Array where equations will be stored while True: test = Poly(divid[-1], x) if len(test.coeffs()) > 1: q, r = div(divid[-2], divid[-1], x) # Taking quotient and remainder of dividing divid.append(-1 * r) else: break print('\n Let\'s calculate dividing of a polynomials: ') for i in divid: print('f' + str(divid.index(i)) + '(x): ' + str(i)) # Create information table table = [[' '], ['-inf'], ['+inf']] for i in divid: table[0].append('f' + str(divid.index(i)) + '(x)') # Better information association test = Poly(i, x) # -inf if (test.degree() % 2 == 0 and test.coeffs()[0] > 0) or \ (test.degree() % 2 != 0 and test.coeffs()[0] < 0): table[1].append('+') else: table[1].append('-') # +inf if test.coeffs()[0] > 0: table[2].append('+') else: table[2].append('-') qwe = changes(table) mininf = qwe[0] plusinf = qwe[1] # Add found data to a table for better user experience table[0].append('Sign changes') table[1].append(mininf) table[2].append(plusinf) print('---------') print( '\n\n Then we need to calculate number of sign changes for (-inf) and (+inf) cases. ' ) print(' Let\'s create a table to visualize our results: ') for i in table: print() for j in i: if table.index(i) == 0: print(' ' + j, end='') else: print(j, end=' ' + ' ' * i.index(j)) print( '\n\n As we see, our equation has {0} - {1} = {2} real roots.'.format( mininf, plusinf, mininf - plusinf)) print('---------') print('\n\n Now we need to define possible intervals for roots. ') print( ' Let\'s create a table with calculated functions in possible root interval. ' ) # Creating a table results = [[' ']] for i in divid: results[0].append('f' + str(divid.index(i)) + '(x) ') # Better information association for i in range(floor(Rlo), ceil(Rup + 1)): results.append(['x = ' + str(i)]) # Calculate value for each function and possible variable count = 1 for j in range(floor(Rlo), ceil(Rup + 1)): for i in divid: if i.evalf(subs={x: j}) > 0: results[count].append('+') else: results[count].append('-') count += 1 # Check number of sign changes ert = changes(results) results[0].append('Sign changes') for i in range(1, len(results)): results[i].append(ert[i - 1]) # Printing table for i in results: print() for j in i: if results.index(i) == 0: print(' ' + j, end='') else: print(j, end=' ' + ' ' * i.index(j)) send = [] for i in range(1, len(results) - 1): if results[i][-1] != results[i + 1][-1]: temp = [i for i in range(floor(Rlo), ceil(Rup + 1))] send.append((temp[i - 1], temp[i])) # Check if we need extended computations analys = False for i in range(1, len(send)): if send[i][0] == send[i - 1][1]: analys = True break if len(send) != mininf - plusinf or analys is True: print( '\n\nWARNING!!! PROGRAM CALCULATE VALUES FROM {0} TO {1} with step 0.1. IT\'S NOT SHOWN IN A TABLE.' .format(floor(Rlo), ceil(Rup + 1)) + '\nIT HAPPENS BECAUSE TWO OR MORE ROOTS LIE IN INTERVAL WITH SIZE LESS THAN 1' + '\nOR THEIR INTERVALS STARTS AND BEGINS AT ONE POINT RESPECTIVELY.' + '\nWITHOUT THIS CHECKING CALCULATIONS WILL BE WRONG.') send = deepanalysis(divid) print('\n As we can see, roots of equation lie in intervals: ') for i in send: print(i) return send # Return intervals of roots
from sympy.abc import x, a, b i, a, b, x = symbols('i, a, b, x') p = x**7 - (S(7) / 9) * x**5 + S(7) / 13 ## ## Ο πίνακας "orismata" περιλαμβάνει τον κάθε όρο του πολυωνύμου που πρόκειται να επεξεργαστούμε ## orismata = p.args orismata = np.array(orismata) print('Mononuma tou poluonumou:', orismata, '\n') p = Poly(p, x) s = p.coeffs() ###### Πίνακας συντελεστών πολυωνύμου s = np.array(s) print('Οι συντελεστές του αρχικού πολυωνύμου:', s) k = np.zeros(len(orismata)) ###### Πίνακας δυνάμεων πολυωνύμου StirList = np.zeros((len(orismata))) k = k.astype(int) Lista = list() for i in range(0, len(orismata)): if degree(orismata[i]) == 0: k[i] = 0 k[i] = degree(orismata[i]) k.sort(axis=-1, kind='quicksort', order=None) k = k[::-1] print('\nΟι βαθμοί των μονωνύμων είναι:', k, '\n')
class MyClass(object): y = [] x = [] xQueries = [] yQueries = [] xCurve = [] yCurve = [] newton_Differences = [] method = 0 exeTime = 0 polynomialFunction = 0 lagranges = [] ax = 0 def __init__(self, newX=[], newY=[], newXQueries=[], newMethod=0): self.x = newX self.y = newY self.xQueries = newXQueries self.method = newMethod if self.method == 0: print("default") elif self.method == 2: print("Lagarange") else: self.newton_Differences = self.getNewtonDifferences( self.x, copy.deepcopy(self.y)) def interpolate(self): self.exeTime = time.time() fig, self.ax = plt.subplots() tempSym = Symbol('x') tempFuncSymbol = self.getFunction(self.x, self.y) self.polynomialFunction = Poly(tempFuncSymbol, tempSym) self.polynomialFunction = Poly( self.getProberFormat(self.polynomialFunction.coeffs()), tempSym) self.getCurvePoints() self.getQueries() self.plot() def getInterpolationValue(self, value=0.0, x=[0.0], y=[]): result = 0.0 if self.method == 2: for i in range(0, len(x), 1): result += self.getValueOfP(value, x, y, i) else: for i in range(0, len(self.newton_Differences), 1): result += self.getProperFactor(self.newton_Differences[i], i, value, x) return result def getNewtonDifferences(self, x=[0.0], y=[0.0]): it = int((len(y) * (len(y) - 1)) / 2) length = len(y) j = 0 i = 0 k = 1 l = 0 for _ in range(0, it, 1): y.append((y[j + 1] - y[j]) / (x[i + k] - x[i])) j += 1 i += 1 l += 1 if l is length - k: j += 1 l = 0 i = 0 k += 1 differences = [] j = 1 i = length differences.append(y[0]) while i < len(y): differences.append(y[i]) i += length - j j += 1 return differences def getProperFactor(self, differences=0.0, noMul=0, value=0.0, x=[0.0]): result = differences for i in range(0, noMul, 1): result *= (value - x[i]) return result def getFunction(self, x=[0.0], y=[]): result = 0.0 if self.method == 2: for i in range(0, len(x), 1): result += self.getValueOfMultiplyingOuts(x, y, i) else: for i in range(0, len(self.newton_Differences), 1): result += self.getProperFactorFunc(self.newton_Differences[i], i, x) return result def getProperFactorFunc(self, differences=0.0, noMul=0, x=[0.0]): result = differences value = Symbol('x') for i in range(0, noMul, 1): result *= (value - x[i]) return result def getProberFormat(self, array=[]): formatedArray = [] for i in array: if i == 0: formatedArray.append(i) continue prec = math.log10(math.fabs(i)) if prec > 0: formatedArray.append(float(i).__format__(".2f")) else: formatedArray.append( float(i).__format__("." + str(int(math.fabs(prec)) + 1) + "f")) return formatedArray def getCurvePoints(self): self.xCurve = [] self.yCurve = [] step = .00001 * (self.x[len(self.x) - 1] - self.x[0]) val = self.x[0] + step while val <= self.x[len(self.x) - 1]: self.xCurve.append(val) self.yCurve.append(self.getInterpolationValue(val, self.x, self.y)) val = val + step def getQueries(self): self.yQueries = [] for i in self.xQueries: self.yQueries.append(self.getInterpolationValue(i, self.x, self.y)) def getValueOfP(self, value=0.0, x=[0.0], y=[0.0], i=0.0): result = y[i] for j in range(0, len(y), 1): if j is i: continue result *= (value - x[j]) / (x[i] - x[j]) return result def getValueOfMultiplyingOuts(self, x=[0.0], y=[0.0], i=0.0): value = Symbol('x') result = y[i] for j in range(0, len(y), 1): if j is i: continue result *= (value - x[j]) / (x[i] - x[j]) return result def getValueOfLagrange(self, x=[0.0], i=0.0): result = 1 value = Symbol('x') for j in range(0, len(x), 1): if j is i: continue result *= (value - x[j]) / (x[i] - x[j]) return result def getAllLagranges(self): sym = Symbol('x') self.lagranges = [] for i in range(0, len(self.x), 1): l = self.getValueOfLagrange(self.x, i) lPoly = Poly(l, sym) cLpoly = self.getProberFormat(lPoly.coeffs()) self.lagranges.append("L" + str(i) + "(x)= " + str(Poly(cLpoly, sym))[5:-17]) def plot(self): self.ax.plot(self.xCurve, self.yCurve, 'gold') self.ax.plot(self.x, self.y, 'ro') print(self.xQueries) print(self.yQueries) self.ax.plot(self.xQueries, self.yQueries, 'k*') bbox_props = dict(boxstyle="round", fc="cyan", alpha=.1) for i in range(0, self.xQueries.__len__(), 1): self.ax.text(self.xQueries[i], self.yQueries[i], "\n(" + str(self.xQueries[i]) + ", " + str(self.yQueries[i].__format__(".2f")) + ")", horizontalalignment='center', verticalalignment='top', fontsize=7, color="black", bbox=bbox_props) #self.ax.text((min(self.x) + max(self.x)) / 2, min(self.yCurve), "P(x) = " + str(self.polynomialFunction)[5:-17], horizontalalignment='center', verticalalignment='top', fontsize=10, color="blue") if self.method == 2: self.getAllLagranges() #print(self.lagranges) plt.title('Lagrange') plt.figure(1).canvas.set_window_title( 'Interpolation fig - Lagrange') else: tempDiff = self.getProberFormat(self.newton_Differences) # self.ax.text((min(self.x) + max(self.x)) / 2, min(self.yCurve), "\nDivided Differences: "+ str(tempDiff), horizontalalignment='center', verticalalignment='top', fontsize=10, color="blue") plt.title('Newton') plt.figure(1).canvas.set_window_title("Interpolation fig - Newton") self.exeTime = time.time() - self.exeTime print("Execution Time: " + str(self.exeTime) + " S") plt.xlabel("x") plt.ylabel("f(x)") #plt.show() def getDif(self): return self.newton_Differences def getLag(self): return self.lagranges def getTime(self): return self.exeTime def showplt(self): plt.show() def getFunc(self): return self.polynomialFunction def getQueryResult(self): return self.xQueries, self.yQueries
import numpy as np a, b, T, s, w, x, z, I = symbols('a b T s w x z I') bilinear_transform = {s : 2/T*(z-1)/(z+1)} # Continuous time transfer function from I(s) to w(s) of the following plant # model: # dw/dt = a*w + b*I G_s = b/(s-a) G_z_num, G_z_den = G_s.subs(bilinear_transform).as_numer_denom() G_z_den = Poly(G_z_den, z) G_z_num = Poly(G_z_num / G_z_den.LC(), z) # divide by leading coefficient of den G_z_den = G_z_den.monic() # make denominator monic assert(G_z_den.coeffs()[0] == 1) kp = Poly(G_z_num.coeffs()[0], z) G_z_N_p = G_z_num - kp * G_z_den print(kp) print(G_z_N_p) print(G_z_den) from sympy import symbols, Poly import numpy as np a, b, T, s, w, x, z, I = symbols('a b T s w x z I') bilinear_transform = {s : 2/T*(z-1)/(z+1)} # Continuous time transfer function from I(s) to w(s) of the following plant