Monday, June 27, 2016

Practice Polynomials for Finding Rational Roots, Repeated Roots

Practice Polynomials for Finding Rational Roots, Repeated Roots
In [13]:
import numpy as np
import random

# r1 is a non-zero integer rational root
r1 = random.choice([-9,-8,-7,-6,-5,-4,-3,-2,-1,1,2,3,5,6,7,8,9])
p1 = np.poly1d([1,r1])

# sometimes make r2 a repeat of r1, otherwise small random integer rational root
if (random.choice([0,1])==1):
    r2=r1
else: 
    r2=random.choice([-5,-4,-3,-2,-1,1,2,3,5])
p2 = np.poly1d([1,r2])

# sometimes make r3 a repeat of r2, otherwise small random integer rational root
if (random.choice([0,1])==1):
    r3=r2
else: 
    r3=random.choice([-5,-4,-3,-2,-1,1,2,3,5])
p3 = np.poly1d([1,r3])

# three small random coefficients, no restriction to rational roots    
c2=random.choice([-5,-4,-3,-2,-1,0,1,2,3,5])
c1=random.choice([-5,-4,-3,-2,-1,0,1,2,3,5])
c0=random.choice([-5,-4,-3,-2,-1,0,1,2,3,5])
p4 = np.poly1d([c2,c1,c0])

p12 = np.polymul(p1,p2)
p34 = np.polymul(p3,p4)

p1234 = np.polymul(p12,p34)
pprime = np.polyder(p1234)
p2prime = np.polyder(pprime)

print("\nPolynomial: \n",p1234)
print("\nFactors:")
print(p1)
print(p2)
print(p3)
print("\n",p4)
print(np.roots([c2,c1,c0]))
print("\nFirst Derivative: \n",pprime)
print("\nSecond Derivative: \n",p2prime)
Polynomial: 
    5      4      3      2
5 x - 29 x + 38 x + 18 x - 27 x + 27

Factors:
 
1 x + 1
 
1 x - 3
 
1 x - 3

    2
5 x - 4 x + 3
[ 0.4+0.66332496j  0.4-0.66332496j]

First Derivative: 
     4       3       2
25 x - 116 x + 114 x + 36 x - 27

Second Derivative: 
      3       2
100 x - 348 x + 228 x + 36