restart:# ADAPTIVE QUADRATURE ALGORITM 4.3 # # To approximate I = integral ( ( f(x) dx ) ) from a to b to within# a given tolerance TOL:## INPUT: endpoints a, b: tolerance TOL: limit N to number of levels## OUTPUT: approximation APP or message that N is exceeded.print(`This is Adaptive Quadrature with Simpson's Method.`):print(`Input the function F(x) in terms of x`):print(`For example: cos(x)`):F := scanf(`%a`)[1]:print(`F(x) = `):print(F):F := unapply(F,x):OK := FALSE:while OK = FALSE doprint(`Input lower limit of integration and `):print(`upper limit of integration`):print(`separated by a blank`):AA := scanf(`%f`)[1]:BB := scanf(`%f`)[1]:print(`a = `):print(AA):print(`b = `):print(BB):if AA > BB thenprint(`Lower limit must be less than upper limit`):elseOK := TRUE:fi:od: OK := FALSE:while OK = FALSE doprint(`Input tolerance.`):EPS := scanf(`%f`)[1]:print(`Tolerance = `):print(EPS):if EPS > 0 thenOK := TRUE:elseprint(`Tolerance must be positive.`):fi:od:OK := FALSE:while OK = FALSE doprint(`Input the maximum number of levels.`):N := scanf(`%d`)[1]:print(`Maximum number of levels = `):print(N):if N > 0 thenOK := TRUE:elseprint(`Number must be positive`):fi:od:if OK = TRUE thenCNT := 0:OK := TRUE:# Step 1APP := 0:I1 := 1:TOL[I1] := 10*EPS:A[I1] := AA:H[I1] := 0.5*(BB-AA):FA[I1] := F(AA):CNT := CNT+1:FC[I1] := F((AA+H[I1])):CNT := CNT+1:FB[I1] := F(BB):CNT := CNT+1:# Approximation from Simpson's method for entire intervalS[I1] := H[I1]*(FA[I1]+4*FC[I1]+FB[I1])/3:L[I1] := 1:# Step 2while I1 > 0 and OK = TRUE do# Step 3FD := F((A[I1]+0.5*H[I1])):CNT := CNT+1:FE := F((A[I1]+1.5*H[I1])):CNT := CNT+1:# Approximations from Simpson's method for halves of intervalsS1 := H[I1]*(FA[I1]+4*FD+FC[I1])/6:S2 := H[I1]*(FC[I1]+4*FE+FB[I1])/6:# Save data at this levelV[0] := A[I1]:V[1] := FA[I1]:V[2] := FC[I1]:V[3] := FB[I1]:V[4] := H[I1]:V[5] := TOL[I1]:V[6] := S[I1]:LEV := L[I1]:# Step 4# Delete the levelI1 := I1-1:# Step 5if abs(S1+S2-V[6]) < V[5] thenAPP := APP+(S1+S2):elseif LEV >= N thenOK := FALSE:# Procedure failselse# Add one level# Data for right half subintervalI1 := I1+1:A[I1] := V[0]+V[4]:FA[I1] := V[2]:FC[I1] := FE:FB[I1] := V[3]:H[I1] := 0.5*V[4]:TOL[I1] := 0.5*V[5]:S[I1] := S2:L[I1] := LEV+1:I1 := I1+1:# Data for left half subintervalA[I1] := V[0]:FA[I1] := V[1]:FC[I1] := FD:FB[I1] := V[2]:H[I1] := H[I1-1]:TOL[I1] := TOL[I1-1]:S[I1] := S1:L[I1] := L[I1-1]:fi:fi:od:if OK = FALSE thenprint(`Level exceeded. Method failed to produce accurate approximation.`):elseOUP := default:fprintf(OUP,`Adaptive Quadrature\134n`):fprintf(OUP,`\134nThe integral of F from %12.8f to %12.8f is\134n`, AA, BB):fprintf(OUP,`%12.8f to within %14.8e\134n`, APP, EPS):fprintf(OUP,`The number of function evaluations is: %d\134n`, CNT): fi:fi:JSFH