Thompson - Computing for Scientists and Engineers (523188), страница 19
Текст из файла (страница 19)
In C the most straightforward, readable, and efficient way to choosewhich of the functions is to be executed in a given run of the program is to use theswitch statement. This is used twice, once near the top of the program to select theoutput file name, and once for each value of x to select the function to be evaluated.3.5 TESTING THE CONVERGENCE OF SERIES93In the following program the functions for the hyperbolic power series have notbeen included. There are therefore six choices of function rather than eight.PROGRAM 3.4 Composite program for power-series expansions.#include#include<stdio.h><math.h>main(){/* Power Series Convergence */FILE *fout;doublepi,xmin,dx,xmax,x,series,func,error;int kmax,choice;char wa;double PSexp(),PScos(),PSsin(),PSarccos(),PSarcsin(),PSln();pi = 4*atan(l.O);printf("Power Series Convergence\n");printf("\nChoose function:");printf("\nl exp x2 cos x3 sin x");printf("\n4 acos x5 asin x6 1n(l+x) : ");scanf("%i",&choice) ;if ( choice < 1 || choice > 6 ){printf("\n !! Choice=%i is <1 or >6",choice);exit(l);}printf("\nWrite over output (w) or Add on (a): ");scanf ("%s", &wa) ;switch (choice){case 1: fout = fopen("PSEXP",&wa); break;case 2: fout = fopen("PSCOS",&wa); break;case 3: fout = fopen("PSSIN",&wa); break;case 4: fout = fopen("PSACOS",&wa); break;case 5: fout = fopen("PSASIN",&wa); break;case 6: fout = fopen("PSLN",&wa); break;}xmax = 2;while(xmax!=O){printf("\n\nInput xmin,dx,xmax (xmax=0 to end),kmax:\n");scanf("%lf%lf%lf%i",&xmin,&dx,&xmax,&kmax);if ( xmax == 0 ){POWER SERIES94printf("\nEndexit (0) ;PowerSeriesConvergence");for ( x = xmin; x <= xmax; x = x+dx ){switch (choice)case 1: series = PSexp(x,kmax);break;func = exp(x);case 2: series = PScos(x,kmax);func = cos(x);break;case 3: series = PSsin(x,kmx);func = sin(x);break;case 4: series = PSarccos(pi,x,kmax,PSarcsin);func = acos(x); break;case 5: series = PSarcsin(x,kmax);func = asin( break;case 6: series = PSln(x,kmax);func = log(l+x); break;error = func-series;printf("\n%g %g %g",x,series,error);fprintf(fout,"%g %g %g\n",x,series,error);}}}double PSexp(x,kmax)/* Power Series for exponential */double x;int kmax;double term,sum;int k;term=1; sum = 1; /* initialize terms & sum */for ( k =l ; k <= krmax; k++ )term = x*term/k;sum= sum+term;}return sum;}doublePScos(x,kmax)3.5 TESTING THE CONVERGENCE OF SERIES/* Power Series for cosine */double x;int kmax;doubleint k;xs,term,sum;xs = x*x;term = 1; sum = 1; /* initialize terms & sum */for ( k = 1; k <= kmax; k++ )term = -xs*term/ (2*k*(2*k-1) );sum = sum+term;return sum;double PSsin(x,kmax)/* Power Series for sine */double x;int kmax;doubleint k;xs,term,sum;xs = x*x;term = 1; sum = 1; /* initialize terms & sum */for ( k = 1; k <= kmax; k++ )term = -xs*term/(2*k*(2*k+l));sum= sum+term;return x*sum;double PSarccos(pi,x,kmax,arcsin)/* Arccosine uses PSarcsin series for arcsin parameter */double pi,x;int kmax;double (*arcsin) (); /* passing function pointer as parameter */if ( fabs(x) >= 1 )printf("\n\n !! In PSarccos x=%g so |x|>=l.
Zero returned",x);9596POWER SERIESreturn 0;elsereturn pi/2-(*arcsin) (x,kmax);if ( x < 1/sqrt(2) )elsereturn (*arcsin) (sqrt(1-x*x) ,kmax);double PSarcsin(x,kmax)/* Power Series for arcsine */double x;int Kmax;doubleint k;xs,term,sum;if ( fabs(x) >= 1 )printf("\n\n !! In PSarcsin x=%g so |x|>=l. Set to zero",x);return 0;}elsexs = x*x;term = 1; sum = 1; /* initialize terms & sum */for ( k = 1; k <= kmax; k++ )term = xs*term*pow( (2*k-1),2)/(2*k*(2*k+l));sun= sum+term;return x*sum;double PSln(x,kmax)/* Power Series for ln(1+x) */double x;int kmax;double power,sum;int k;if ( fabs(x) >= 1 )3.5 TESTING THE CONVERGENCE OF SERIES97print f("\n\n !! In PSln x=%g so |x|>=l.
Zero returned",x);return 0;elsepower = 1; sum = 1; /* initialize terms & sum *lfor ( k = 1; k <= (kmax-1); k++ )power = -x*power;sum = sum+power/(k+l);return x*sum;A few checks should be made on your completed Power Series Convergenceprogram. For example, check that the range of choice is correctly tested as soon asit is input, check that the correct files are then opened, and that the correct function iscalled for a given value of choice.
Also check that the x loop is correctly executedand controlled, including graceful termination if xmax is entered as zero.With these quick and simple checks out of the way, you are ready to explore thenumerical properties of power-series expansions.Using the program to test series convergenceHaving the completed Program 3.4 for testing the convergence of power series ofuseful functions, we are ready to exercise the computer (and our brains) to test theconvergence properties numerically.Exercise 3.37(a) For input x values in the range zero to /2 for the cosine and sine, and in therange zero to less than unity for the arcsine and logarithm, check the convergence of their power series as a function of varying the upper limit of the summation, kmax.
Compare your results with those in Figures 3.9, 3.10, 3.11, and3.12. What do you conclude about the rate of convergence of each series, andwhat is the reason for this convergence behavior?(c) Modify Power Series Convergence so that for a given x the power series for both cos x and sin x are computed. The program should then squarethe series values, add them, then subtract the result from unity. As you changekmax, how rapidly does the result approach zero, which is what the theorem ofPythagoras, (2.43), predicts?(d) Modify the program so that for a given x the power series expansions ofboth ln (1 + x ) and ln (1 - x ) are computed.
As you change kmax, how98POWER SERIESrapidly does each power-series result approach zero, and for x > 0 (but lessthan un ity) why is the convergence of the second series much slower? nAnother numerics question is worthy of exploration with this program. Namely,how sensitive are the power series results to the effects of roundoff errors in thecomputer arithmetic? If you understand numerical noise in computing, you mightinvestigate this topic now. It is covered in Section 4.2 as a preliminary to discussing numerical derivatives and integrals.From our extensive discussions in this chapter on power series, from their analysis, numerics, and applications, you will appreciate their importance when computing numerically. Ideas and techniques from power series are used widely in thechapters that follow.REFERENCES ON POWER SERIESCody, W.
J., and W. Waite, Software Manual for the Elementary Functions,Prentice Hall, Englewood Cliffs, New Jersey, 1980.Hofstadter, D. R., Gödel, Escher, Bach: An Eternal Golden Braid, Basic Books,New York, 1979.Kellison, S. G., The Theory of Interest, Irwin, Homewood, Illinois, 1970.Kernighan, B. W., and D.
M. Ritchie, The C Programming Language, PrenticeHall, Englewood Cliffs, New Jersey, second edition, 1988.Lindstrom, P. A., “Nominal vs Effective Rates of Interest,” UMAP Module 474, inUMAP Modules Tools for Teaching, COMAP, Arlington, Massachusetts, 1987,pp. 21-53.Miller, W., The Engineering of Numerical Software, Prentice Hall, EnglewoodCliffs, New Jersey, 1984.Paeth, A. W., “A Fast Approximation to the Hypotenuse.” in A. S. Glassner, Ed.,Graphics Gems, Academic, Boston, 1990, pp. 427 - 431.Polya, G., How to Solve It, Doubleday Anchor Books, New York, second edition,1957.Protter, M. H., and C.
B. Morrey, Intermediate Calculus, Springer-Verlag, NewYork, second edition, 1985.Rucker, R., The Fourth Dimension, Houghton Mifflin, Boston, 1984.Taylor, A. E., and W. R. Mann, Advanced Calculus, Wiley, New York, thirdedition, 1983.Wolfram, S., Mathematica: A System for Doing Mathematics by Computer,Addison-Wesley, Redwood City, California, second edition, 1991.Previous Home NextChapter 4NUMERICAL DERIVATIVES AND INTEGRALSThe overall purpose of this chapter is to introduce you to methods that are appropriate for estimating derivatives and integrals numerically. The first, and very important, topic is that of the discreteness of numerical data, discussed in Section 4.2.This is related in Section 4.3 to the finite number of significant figures in numericalcomputations and to the consequent problem of the increase in errors that may becaused by subtractive cancellation.With these precautions understood, we are prepared by Section 4.4 to investigate various schemes for approximating derivatives and to develop a C program tocompute numerical derivatives, a topic that is explored further in Project 4A in Setion 4.5.
Numerical integration methods, including derivation of the trapezoid ruleand Simpson’s formula, are developed and tested in Section 4.6 and applied in Project 4B (Section 4.7) on the electrostatic potential from a line charge. Referenceson numerical derivatives and integrals round out the chapter.We must emphasize here a profound difference between differentiation and integration of functions.
Analytically, for a function specified by a formula its derivatives can almost always be found by using a few direct algorithms, such as those fordifferentiation of products of functions and for differentiating a function of a function. By contrast, the same function may be very difficult (if not impossible) to integrate analytically. This difference is emphasized in Section 3.5 of Wolfram’s book,where he describes the types of integrals that Mathematica can and cannot do.Numerically, the situation with respect to differentiation and integration is usually reversed.
As becomes clear in Sections 4.4 and 4.5, the accuracy of numericaldifferentiation is sensitive to the algorithms used and to the numerical noise in thecomputer, such as the finite computing precision and subtractive cancellation errorsdiscussed in Section 4.3. On the other hand, almost any function that does not oscillate wildly can be integrated numerically in a way that is not extremely sensitive tonumerical noise, either directly or by simple transformations of the variables of integration.99100NUMERICAL DERIVATIVES AND INTEGRALSOther methods for differentiating and integrating discretized functions by usingsplines are presented in Sections 5.4 and 5.5.