/************************************************ Treibergs Jan 24, 2006 HW 2a Newton's series for pi sum8.c ************************************************/ /* Newton's series may be given by S = a_1 + a_2 + a_3 + a_4 + a_5 + ... where a_1 = 3 a_2 = 3/(3*2^3) a_3 = 3*3/(4*5*2^5) a_4 = 3*3*5/(4*6*7*2^7) a_5 = 3*3*5*7/(4*6*8*9*2^9) ... To see the pattern, it is easier to look at b_i where a_i = b_i/(2*i-1) so that b_1 = 3 b_2 = 3/(2^3) = 1*[3]/8 b_3 = 3*3/(4*2^5) = 3*[3/(2^3)]/(2*8) b_4 = 3*3*5/(4*6*2^7) = 5*[3*3/(4*2^5)]/(3*8) b_5 = 3*3*5*7/(4*6*8*2^9) = 7*[3*3*5/(4*6*2^7)]/(4*8) Thus b_i satisfies the recursion b_1 = 3 and b_(i+1) = (2*i-1)*b_i/(i*8) for i=1,2,3,.... Thus a and b are b_i and a_i at the beginning of the do-while loop, as the index i runs from 1 to 20. */ # include # include # include int main (void) { int i, n; double a, b, sum; i = 1; n = 20; sum = 0.0; b = 3.0; printf (" n Term Sum\n"); do { a = b/(2*i-1); sum = sum+a; printf ("%4d%20.15lf%20.15lf\n", i, a, sum); b = (2*i-1)*b/(8*i); i = i+1; } while ( i <= n ); printf ("The actual value of pi is%19.15lf\n", M_PI); return EXIT_SUCCESS; } /************************************************ Treibergs Jan 24, 2006 HW 2b Power series for cosine sum8.c ************************************************/ /* Maclaurin's series for cosine is given by S = a_0 + a_1 + a_2 + a_3 + a_4 + ... where a_0 = 1 a_1 = -x^2/2 = -x^2*[1]/(1*2) a_2 = x^4/(2*3*4) = -x^2*[-x^2/2]/(3*4) a_3 = -x^6/(2*3*4*5*6) = -x^2*[x^4/(2*3*4)]/(5*6) a_4 = x^8/(2*3*4*5*6*7*8) = -x^2*[-x^6/(2*3*4*5*6)]/(7*8) ... Thus a_i satisfies the recursion a_0 = 1 and a_i = -x^2*a_(i-1)/((2*i-1)*(2*i)) for i=1,2,3,.... The partial sums S_n = a_1 + ... + a_n corresponds to the Taylor polynomials p_{2n} = p_{2n+1} = S_n of degrees 2n and 2n+1 since the series consists only of even terms. Thus the remainder | cos(x) - S_n | = | cos(x) - p_{2n+1} | = | R_{2n+1} |. For a general function f(x), the error term (the Lagrange formula for the remainder) is f(x) - p_{2n+1}(x) = R_{2n+1} = f^{2n+2}(c) x^{2n+2}/(2n+2)! where c is a number strictly between 0 and x. But if f(x)=cos(x), | f^{2n+2}(c) |=| cos(c) | <= 1 so |R_{2n+1}| <= |x|^{2n+2}/(2n+2)! = |p_{2n+2}| = |a_{n+1}|. Thus in this instance, the error has the magnitude of the next term neglected. Thus the term on the next line is printed first as the error on the current line. */ # include # include # include int main(void) { int i=1, n=20; double x, y, a, sum; a = 1.0; sum = a; printf ("What is your angle in radians?"); scanf ("%lf", &x); y = -x*x/2.0; printf ("\n n\t\t Term\t\t Sum\t\t\t Error\n"); printf ("%4d%22.15lf%22.15lf", 0, a, sum); do { a = y*a/(i*(2*i-1)); sum = sum+a; printf ("%22.15lf\n%4d%22.15lf%22.15lf",fabs(a),i,a,sum); i = i+1; } while ( i <= n); printf ("%22.15lf\n", fabs( y*a/(i*(2*i-1))) ); printf (" Actual cos(%10.6lf) is%20.15lf\n", x, cos(x) ); return EXIT_SUCCESS; }