I was tasked with writing a function on Mathematica similar to NIntegrate
, but that uses the Composite Simpson's Rule as its method for doing the calculation. The function should take as arguments, the function to be integrated (aka the integrand), the integration variable (as well as its upper and lower limits) and how many equally spaced subdivisions it should use to do the calculation.
The function is only required to integrate in regards to one variable; however, if presented with a multivariable function it must be able to integrate over only one designed variable and ignore the others.
I was able to handle that following another question here. And came up with the following code:
SetAttributes[SimpsonIntegral, HoldAll]
SimpsonIntegral[f_[a___, var_, b___], {var_, xmin_, xmax_}, steps_] :=
(xmax - xmin)/(3 steps) Sum[f[a, xmin + (xmax - xmin)/steps (2*y - 2), b] +
4*f[a, xmin + (xmax - xmin)/steps (2*y - 1), b] +
f[a, xmin + (xmax - xmin)/steps (2*y), b], {y, 1, steps/2}];
It worked perfectly fine with single variable functions (like Sin[x]
) and even multivariable functions (like BesselJ[n,z]
). However, it fails when the input function takes an expression as its argument. For example:
SimpsonIntegral[Sin[x - 1], {x, 0, 1}, 6]
would simply return unevaluated:
SimpsonIntegral[Sin[x - 1], {x, 0, 1}, 6]
instead of the various terms of the sum.
How can I fix this?
SimpsonIntegral[2, {x, 0, 1}, 4]
is not expected to evaluate? $\endgroup$a, b
in your function? $\endgroup$