from math import *; # calculating cos(x) in different ways # rounding and truncation error # roundp rounds x to p signficant digits, assuming 0<= x < 1 def roundp(x,p): return round(x*pow(10,p-1))/pow(10,p-1); # cos hat e, i.e. "exact" arithmetic for Taylor approximation of cos def Taylore(x): return 1 - x*x/2; # cos hat, i.e. Taylor approximation, with p significant digits def Taylor(x,p): x1 = roundp(x,p); x2 = roundp(x1*x1,p); x3 = roundp(x2/2,p); x4 = roundp(1-x3,p); return x4; p = 3; # precision, try 2-5 x = 0.1; # input, try different values, e.g. 0.1, 0.2, 0.5, 1 print("input x: ", x); print("precision p: ", p); print("cos(x): ", cos(x)); print("Taylor_e(x) [(1-x^2/2), exact]: ", Taylore(x)); print("Taylor(x) [(1-x^2/2), precision p]", Taylor(x,p)); print("Rounding Error = Taylor(x) - Taylore(x) = ", Taylor(x,p) - Taylore(x)); print("Truncation Error = Taylore(x) -cos(x) = ", Taylore(x) - cos(x)); print("Computational Error = RE + TE = Taylor(x) - cos(x) = ", Taylor(x,p) - cos(x));