update hw5q4

This commit is contained in:
2025-09-30 20:56:33 -04:00
parent 4b07a0bd0d
commit f5665dc3a8
3 changed files with 33 additions and 0 deletions

31
homework5/Homework5_Q4.py Normal file
View File

@@ -0,0 +1,31 @@
import numpy as np
import matplotlib.pyplot as plt
def question_4():
# x = 1.920 -> 2.080 (included) step = 0.001
x = np.arange(1.920, 2.081, 0.001)
# p = [1, -18, 144, -672, 2016, -4032, 5376, -4608, 2304, -512]
# from x^9 to x^0
coeffs = [1, -18, 144, -672, 2016, -4032, 5376, -4608, 2304, -512]
p_coeff = np.polyval(coeffs, x)
# p(x) = (x-2)^9
p_fact = (x - 2.0) ** 9
plt.plot(x, p_coeff, label='Coefficient Form', lw=2)
plt.plot(x, p_fact, label='Factored Form', lw=2, ls='--')
plt.yscale('symlog', linthresh=1e-10)
plt.xlabel('x', fontsize=14)
plt.ylabel('p(x)', fontsize=14)
plt.title('Comparison of Polynomial Forms', fontsize=16)
# save the figure
plt.legend(fontsize=12)
plt.grid(True, which='both', ls='--', lw=0.5)
plt.savefig('question4.png')
plt.show()
abs_diff = np.abs(p_coeff - p_fact)
rel_diff = abs_diff / (np.abs(p_fact) + 1e-30)
print("Maximum Absolute Difference:", np.max(abs_diff))
print("Maximum Relative Difference:", (abs_diff[np.argmax(np.abs(p_fact))] /
(np.abs(p_fact).max() + 1e-30)))
if __name__ == "__main__":
question_4()

BIN
homework5/question4.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

2
homework5/question4.txt Normal file
View File

@@ -0,0 +1,2 @@
Maximum Absolute Difference: 1.1353085579642377e-11
Maximum Relative Difference: 0.048289188322333074