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?


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[Adaptive[a, c, tol/2] + Adaptive[c, b, tol/2]]];];
f[x_] = Cos[x^2];
Print["f[x] = ", f[x]];
tol1 = 0.001;
count = 0;
Print[Adaptive[0.0, 2.0, tol1, count]];

This ends up returning:

f[x] = Cos[x^2]
  • 2
    $\begingroup$ 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. $\endgroup$ Commented Oct 10, 2016 at 11:17
  • $\begingroup$ 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? $\endgroup$
    – AndreasP
    Commented Oct 10, 2016 at 11:21
  • $\begingroup$ I was studying a book with examples written like this, but I can't seem to get the same answers as the book. $\endgroup$
    – johnson
    Commented Oct 10, 2016 at 11:29

1 Answer 1


There are two mistakes in this expression

If[Abs[Sab - Sac - Scb] < tol,
  Return[Sac + Scb],
  Return[Adaptive[a, c, tol/2] + Adaptive[c, b, tol/2]]];]

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], 
   Return[Adaptive[a, c, tol/2, count] + 
     Adaptive[c, b, tol/2, count]]];]

yields the correct result

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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.