Advertisement
Guest User

real_root_isolation.py

a guest
May 22nd, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.65 KB | None | 0 0
  1. import typing
  2. import sys
  3. import sympy as sp
  4. import numpy as np
  5. from sympy.parsing.sympy_parser import parse_expr
  6.  
  7. x, y = sp.symbols('x y')
  8.  
  9.  
  10. result = []
  11.  
  12.  
  13. def real_root_isolation(p, c, d):
  14.  
  15.     n = p.degree()
  16.     pI = (y + 1)**n * p.subs({x: (c * y + d) / (y + 1)})
  17.     pI_coeffs = sp.Poly.from_expr(pI).simplify().coeffs()
  18.     mu = count_sign_changes(pI_coeffs)
  19.  
  20.     print("intermediate result:", result, "\n")
  21.     print("c:", c, "d:", d)
  22.     print("coefficients:", pI_coeffs)
  23.  
  24.     if mu == 0:
  25.         result.append((c, d, "-> keine Nullstelle"))
  26.         return
  27.     if mu == 1:
  28.         result.append((c, d))
  29.         return
  30.  
  31.     m = (c + d) / 2
  32.     p_at_m = p.evalf(subs={x: m})
  33.     if p_at_m == 0:
  34.         result.append(m)
  35.  
  36.     real_root_isolation(p, c, m)
  37.     real_root_isolation(p, m, d)
  38.  
  39.  
  40. def count_sign_changes(a):
  41.     sign_changes = 0
  42.     last_sign = np.sign(a[0])
  43.  
  44.     for i in range(1, len(a)):
  45.         this_sign = np.sign(a[i])
  46.         if this_sign != last_sign:
  47.             sign_changes += 1
  48.             last_sign = this_sign
  49.     return sign_changes
  50.  
  51.  
  52. def calculate_b(p):
  53.     coeffs = p.coeffs()[::-1]
  54.  
  55.     last = coeffs[len(coeffs) - 1]
  56.  
  57.     l = []
  58.     for i in range(0, len(coeffs)):
  59.         new_element = coeffs[i] / last
  60.         new_element = abs(new_element) # entspricht nicht der Beschreibung auf dem Übungsblatt, aber funktioniert so.
  61.         l.append(new_element)
  62.  
  63.     print(l)
  64.     return 1 + max(l)
  65.  
  66.  
  67. print("Enter Polynomial:")
  68. in_string = sys.stdin.readline()
  69. plnm = sp.Poly.from_expr(parse_expr(in_string))
  70.  
  71. b = calculate_b(plnm)
  72. print("b", b)
  73.  
  74. real_root_isolation(plnm, -b, b)
  75. print(result)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement