Fourth Week Examples: Series and Theoretical Error Bounds


/* Treibergs  1-30-6

Program to sum exponential series 
with Taylor's error

today.c                      */

# include <stdio.h>
# include  <stdlib.h>
# include  <math.h>


int
main(void)
{
    int  i,  n=20;
    double  sum, term,  error, eps,  x,y,z;

    printf ( " Maclaurin Series for the Exponential. \n\n");

    printf ( " Enter the desired accuracy, epsilon : ");
    scanf ( "%lf", &eps);

    printf ( " Enter x : ");
    scanf ( "%lf", &x);

    y = exp(x);
    if( x <= 0.0 )
          z = 1.0;
    else 
          z=exp(fabs(x));
    
    printf(" n\t\t  term\t\t     sum\t\t error \n\n");

    i=0;
    term = 1.0;


    do
    {
        sum = sum + term;
        printf (" %4d %20.15f %20.15f", i, term, sum);
        i = i + 1;
        term = term * x / i;
        error = fabs ( z * term );
        printf (" %21.15f\n", error );
    }
    while( (i <= 20)  && (error >= eps ) );

    printf ( " Actual value of exp(x) = %21.15f\n", y );
    printf ( "     \t\t\t         Actual error = %21.15f\n", sum - y );
    printf ( "        \t\t\t      Epsilon = %21.15f\n", eps );


    return EXIT_SUCCESS;
}




/* Treibergs  2-1-6

Program to sum series for y = 1/(1+x*x)
with Taylor's error

today.c                      */

# include <stdio.h>
# include <stdlib.h>
# include <math.h>

int
main(void)
{
    int  i,  n=20;
    double  sum, term,  error, eps,  x, z, y;

    printf ( " Maclaurin Series for the 1/(1+x*x). \n\n" );

    printf ( " Enter the desired accuracy, epsilon  = " );
    scanf ( "%lf", &eps);

    printf ( " Enter x : " );
    scanf( "%lf", &x);

    y = 1.0 / (1.0 + x*x );
    z = - x*x;
    
    printf ( " n\t\t  term\t\t     sum\t\t error bound \n\n" );

    i = 0;
    term = 1.0;


    do
    {
        sum = sum + term;
        printf ( " %4d %20.15f %20.15f", i, term, sum);
        i = i + 1;
        term = term * z;
        error = fabs ( term );
        printf ( " %21.15f\n", error );
    }
    while( (i <= 20)  && (error >= eps ) );

    printf ( "Actual value of 1/(1+x*x) = %19.15f\n", y);
    printf ( "     \t\t\t         Actual error = %21.15f\n", sum - y );
    printf ( "        \t\t\t      Epsilon = %21.15f\n", eps );

    return EXIT_SUCCESS;
}