# Can't get the correct answer with this Adaptive Simpson's Rule algorithm

I think the mathematical portion of my algorithm is correct, but I don't really know the mathematica syntax.

How do I get the actual function to be evaluated?

Code:

Simpson[a_, b_, count_] := Module[{},
Return[(b - a)/6 (f[a] + 4 f[(a + b)/2] + f[b])]];
Adaptive[a_, b_, tol_, count_] := Module[{c},
c = (a + b)/2;
Sab = Simpson[a, b, count];
Sac = Simpson[a, c, count];
Scb = Simpson[c, b, count];
If[Abs[Sab - Sac - Scb] < tol,
Return[Sac + Scb],
Return[count],
f[x_] = Cos[x^2];
Print["f[x] = ", f[x]];
tol1 = 0.001;
count = 0;


This ends up returning:

f[x] = Cos[x^2]
0

• It'd be nicer if you could post your code in a way that people don't have to retype the whole thing. See this as well. Oct 10, 2016 at 11:17
• Something that strikes me as strange is your ìf that has three expressions within, the last of which is only returned if Abs[Sab-Sac-Scb] doesn't return True or False. Are you sure this is what you wanted? Oct 10, 2016 at 11:21
• I was studying a book with examples written like this, but I can't seem to get the same answers as the book. Oct 10, 2016 at 11:29

There are two mistakes in this expression

If[Abs[Sab - Sac - Scb] < tol,
Return[Sac + Scb],
Return[count],


so first, you have If[condition, expression1, expression2, expression3] where expression3 is only evaluated if condition evaluates neither to True or False. Since that shouldn't happen for a simple numerical comparison, your algorithm was always stuck Returning count which is initialized to 0 so your function returns 0.

Second, your Adaptive demands 4 arguments, you only provide three though. Correcting that, i.e. replacing the above block by

If[Abs[Sab - Sac - Scb] < tol, Return[Sac + Scb],

f[x] = Cos[x^2]

To find errors like these it can help to put some Prints in your function so you can see e.g. how deep you go in the recursive function or whether Simpson returns results that are nonsensical or not.