How do i plot this polynomial fraction using numpy and matplotlib?

Viewed 183

The task is to print quotient and remainder of this polynomial fraction and then plot the original function and the quotient. I figured out how to plot the quotient, but what is the best way to plot f(x)?

import matplotlib.pyplot as plt
import numpy as np

px = np.poly1d([1, -7, 15, -21, 36])
qx = np.poly1d([1, -7, 6])        

hx, rx = np.polydiv(px, qx)

print("\nh(x):")
print("\n", hx)
print("\nr(x):")
print(rx, "\n")

x = np.arange(20)
y = hx(x)
plt.grid(color='black', linestyle='dotted')
plt.plot(x, y)
plt.show()
1 Answers

The simplest way would be to define a x-range and evaluate the function. Straight forward:

import matplotlib.pyplot as plt
import numpy as np

px = np.poly1d([1, -7, 15, -21, 36])
qx = np.poly1d([1, -7, 6])        

hx, rx = np.polydiv(px, qx)

print("\nh(x):")
print("\n", hx)
print("\nr(x):")
print(rx, "\n")

x = np.linspace(0,20,101)
f = (x**4 - 7*x**3 + 15*x**2 - 21*x + 36)/(x**2 - 7*x + 6)
y = hx(x)
plt.grid(color='black', linestyle='dotted')
plt.plot(x, y)
plt.plot(x,f)
plt.show()

enter image description here

Related