def plot(ax): # Declare x to be a sympy symbol, not a python variable x = symbols('x') # Declare the polynomial "fn" by providing the coefficients # of each term in in decreasing (exponent) order fn = Poly([1, -2, -120, 22, 2119, 1980], x) # fn(x) = 2x^3 - 2x^2 - 11x + 52 #fn = Poly([2, -2, -11, 52], x) # fn(x) = 2x^3 - 2x^2 - 11x + 52 # Find the real-only roots of the polynomial # and store in a numpy array of floats fn_zeros = np.asarray([np.float(r) for r in real_roots(fn)]) # Find the symbolic first derivative of "fn" and locate the real-only # zeros of this derivative to find the extrema (tangent) points fn_d1 = Derivative(fn, x, evaluate=True) fn_d1_zeros = np.asarray([np.float(r) for r in real_roots(fn_d1)]) # Combine the zeros of "fn" and the zeros of the derivative of "fn" into a # a single numpy array, then sort that array in increasing order. This array # now contains the x-coordinate of interesting points in the "fn" polynomial x_pts = np.sort(np.concatenate((fn_zeros, fn_d1_zeros))) # Get the minimum and maximum of the interesting points array x_min, x_max = x_pts[0] - 1, x_pts[-1] + 1 print(f"x_min = {x_min:.4f}, x_max = {x_max:.4f}") xa = np.linspace(x_min, x_max, 1000) # Label the graph and draw (0,0) axis lines ax.set_xlabel("x") ax.set_ylabel("y") ax.axhline(0, color='gray') ax.axvline(0, color='gray') # Create a numpy callable (numeric) function from the symbolic "fn" polynomial fn_lambda = lambdify(x, fn.as_expr(), modules='numpy') ax.plot(xa, fn_lambda(xa), linewidth=2) # Plot the zeros and derivative roots on the line graph ax.scatter(fn_zeros, fn_lambda(fn_zeros), color='red') ax.scatter(fn_d1_zeros, fn_lambda(fn_d1_zeros), color='green') # Set the graph title to the polynomial expressed in LaTeX format ax.set_title(f"$y = {latex(fn.as_expr())}$")
def cad(variety_i): f=variety_i.polynomials[0] for pol_j in variety_i.polynomials: f*=pol_j f=f.as_expr().as_poly() roots=sympy.real_roots(f) roots=list(set(roots)) roots.sort() print(roots)
def mandatory(): open("output.txt", "wt").close() try: expr, coefficients = read_input() deriv_coeff = diff(expr, x).all_coeffs() timer = time.perf_counter() g = gcd(coefficients, deriv_coeff) output("gcd", g) coefficients, r = div(coefficients, g) output("f/gcd", coefficients) expr = make_expr(coefficients) output("") output("sympy.roots", real_roots(expr)) output("") R = (abs(coefficients[0]) + max(coefficients)) / abs(coefficients[0]) output("[-R, R]", "[-%s, %s]"%(R, R)) x0s = list() for i in range(tries): x0 = random.uniform(-R, R) while x0 in x0s: x0 = random.uniform(-R, R) x0s.append(x0) results = list() for i in range(tries): res = solve_olver(coefficients, expr, x0s[i]) if res != "divergenta": ok = True for value in results: if abs(res - value) <= epsilon: ok = False if ok is True: results.append(res) output("computed roots", sorted(results)) timer = time.perf_counter() - timer output("") output("time elapsed", timer) if messagebox.askyesno(title="Success", message="Tasks solved successfully.\nTime elapsed: %.3f seconds.\nCheck the output file?"%timer): open_output() except Exception as e: messagebox.showerror(title="Error", message="Invalid input: %s"%e)
def _floor_div_nth_cf__end_v1(poly, q): ''' it seems N(RootOf(...)) is too slow I try to use refine_root instead. ''' rs = real_roots(poly) qt = max(rs) Q = floor(qt) upper = zero_upper_bound_of_positive_poly(poly) ndigit = num_radix_digits(upper, 10) Q = int(neval(Q, ndigit + 3)) assert Q >= 1 assert not poly.subs(q, Q) > 0 assert not poly.subs(q, Q + 1) <= 0 return Q
def get_roots(function): """ Devuelve un diccionario compuesto por las raíces como keys y el tipo de raíz como value (doble, triple, etc). """ domain = get_domain(function) def list_roots_to_dict(values): roots = {} for value in values: if value in domain: roots[value] = 1 # FIXME: En realidad no lo sé return roots try: return list_roots_to_dict(sympy.real_roots(function)) except: try: return list_roots_to_dict(sympy.solve(function, x)) except: return {}
(-F[m - 1] / F[n - 1]))**(1.0 / (n - m)) if q < temp_min: temp_min = q index = n - 1 times_used[index] = times_used[index] + 1 # print times_used if temp_max < temp_min: temp_max = temp_min # print temp_max , times_used return ceiling((65.0 / 64) * (temp_max)) i = 0 for i in range(2): f = random_poly(x, 3, -10**2, 10**2) # f=-22*x**17 + 26*x**16 + 70*x**15 + 91*x**14 - 67*x**13 + 80*x**12 + 81*x**11 + 45*x**10 + x**9 - 77*x**8 + 88*x**7 + 52*x**6 + 82*x**5 - 50*x**4 + 4*x**3 + 27*x**2 + 56*x - 17 print(f) print("The real roots of f are located in the intervals:") print(real_roots(f)) print("bounds using sympy functions") print(dup_root_upper_bound(Poly(f).all_coeffs(), ZZ)) # print(dup_root_lower_bound(Poly(f).all_coeffs(),ZZ)) # print("bounds using giacpy functions") # print(gp.posubLMQ(f,x)) # print(gp.poslbdLMQ(f,x)) print("bounds using upperBound LMQ") print(LMQ(f)) i = i + 1
def real_roots(expression, x): return [i.n() for i in sympy.real_roots(expression, x)]
def qQuadAlphBeta_template(): '''Find Alpha & Beta in Quadratic Equation e.g. The quadratic equation x2 – 6x + 2 = 0 has roots α and β.''' a_part = randint(-10, 10) while a_part == 0 or a_part == 1: a_part = randint(-10, 10) b_part = randint(-100,100) while b_part == 0: b_part = randint(-100,100) c_part = randint(-100,100) #This is so that b^2-4ac is always positive if a_part > 0: c_part = randint(-100, -2) else: c_part = randint(2,100) alpha_str = tostring(am.parse("alpha")) beta_str = tostring(am.parse("beta")) question = "The quadratic equation " question_eqn = None first_qn = tostring(am.parse("alpha+beta")) second_qn = tostring(am.parse("alphabeta")) third_qn = tostring(am.parse("1/(alpha)+1/(beta)")) if b_part > 0 and c_part > 0: question_eqn = tostring(am.parse("%sx^2+%sx+%s=0" % (str(a_part), str(b_part), str(c_part)))) elif b_part > 0 and c_part < 0: question_eqn = tostring(am.parse("%sx^2+%sx%s=0" % (str(a_part), str(b_part), str(c_part)))) elif b_part < 0 and c_part < 0: question_eqn = tostring(am.parse("%sx^2%sx%s=0" % (str(a_part), str(b_part), str(c_part)))) else: question_eqn = tostring(am.parse("%sx^2%sx+%s=0" % (str(a_part), str(b_part), str(c_part)))) question += question_eqn question += " has roots %s and %s." % (alpha_str, beta_str) question += " (i) Find " + first_qn question += " (ii) Find " + second_qn question += " (iii) Find " + third_qn steps = [] ans_val = real_roots(a_part*x**2+b_part*x+c_part) alpha_root, beta_root = ans_val[0], ans_val[1] part_i_ans = simplify(alpha_root + beta_root) part_ii_ans = simplify(alpha_root * beta_root) part_iii_ans = "(%s)/(%s)" % (str(part_i_ans).replace("**","^"), str(part_ii_ans).replace("**","^")) quad_eqn_formula = tostring(am.parse("(-b+-sqrt(b^2-4ac))/(2a)")) steps.append("First find the roots to alpha and beta") steps.append("This is found by using the quadratic formula " + quad_eqn_formula) steps.append("Note discrimant %s has to be +ve to have 2 real roots" % \ tostring(am.parse("b^2-4ac"))) steps.append("%s is in the quadratic form %s" % \ (question_eqn, tostring(am.parse("ax^2+bx+c=0")))) steps.append("As %s is equal to %s, respectively" % \ (tostring(am.parse("a,b,c")), tostring(am.parse("%s,%s,%s" % (str(a_part), str(b_part), str(c_part)))))) steps.append("Substitute %s into %s" % (tostring(am.parse("%s,%s,%s" % (str(a_part), str(b_part), str(c_part)))), quad_eqn_formula)) steps.append("This gives" + tostring(am.parse("(-(%s)+-sqrt((%s)^2-4(%s)(%s)))/(2(%s))" % (str(b_part), str(b_part), str(a_part), str(c_part), str(a_part))))) steps.append("**For our answers, we might have used power of 1/2. Please" + " replace with square root instead") steps.append("Which gives " + tostring(am.parse("%s, %s" % (str(alpha_root).replace("**","^"), str(beta_root).replace("**", "^")))) + " which are the 2 real roots known as alpha and beta") steps.append("Part (i) is solved by " + \ tostring(am.parse("%s+(%s)=%s" % \ (str(alpha_root).replace("**","^"), str(beta_root).replace("**", "^"), str(part_i_ans).replace("**","^"))))) steps.append("Part (ii) is solved by " + \ tostring(am.parse("%s*(%s)=%s" % \ (str(alpha_root).replace("**","^"), str(beta_root).replace("**", "^"), str(part_ii_ans).replace("**","^"))))) steps.append("Part (iii) %s is equivalent to %s therefore using results " \ "from part (i) & (ii): %s" % (third_qn, tostring(am.parse("(alpha+beta)/(alpha*beta)")), tostring(am.parse(part_iii_ans)))) answer = [] answer.append(steps) answer.append(tostring(am.parse(str("%s,%s,%s" % (str(part_i_ans).replace("**","^"), str(part_ii_ans).replace("**","^"), part_iii_ans))))) return question, answer