diff --git a/homework5/Homework5_Q4.py b/homework5/Homework5_Q4.py new file mode 100644 index 0000000..582d207 --- /dev/null +++ b/homework5/Homework5_Q4.py @@ -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() \ No newline at end of file diff --git a/homework5/question4.png b/homework5/question4.png new file mode 100644 index 0000000..44d066b Binary files /dev/null and b/homework5/question4.png differ diff --git a/homework5/question4.txt b/homework5/question4.txt new file mode 100644 index 0000000..58b9893 --- /dev/null +++ b/homework5/question4.txt @@ -0,0 +1,2 @@ +Maximum Absolute Difference: 1.1353085579642377e-11 +Maximum Relative Difference: 0.048289188322333074 \ No newline at end of file