0

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],
    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]
0
johnson
  • 113
  • 4
  • 2
    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. – J. M.'s missing motivation Oct 10 '16 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? – AndreasP Oct 10 '16 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. – johnson Oct 10 '16 at 11:29

1 Answers1

1

There are two mistakes in this expression

If[Abs[Sab - Sac - Scb] < tol,
  Return[Sac + Scb],
  Return[count],
  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]

0.461459

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.

AndreasP
  • 598
  • 4
  • 10