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)