0
$\begingroup$

I created this code to calculate an approximation to an integral, using the Trapezoid Rule and the Midpoint Rule.

Here the output is a table for N=16.

Question: what would be a simple way to create a table multiple values for N? Such as N=4, N=8 and N=16?

Clear["Global`*"]
n := 16
xA := 0
xB := 2
f[t_] := 1 + t^2
int := Integrate[f[t], {t, xA, xB}] // N
h := (xB - xA)/n
xT := xA + h*Range[0, n]
yT := f[xT]
T := h (Total[yT] - 1/2 First[yT] - 1/2 Last[yT]) // N
Terror := int - T
xM := xA + h*(Range[1, n] - 1/2)
yM := f[xM]
M := Total[h*f[xM]] // N
Merror := int - M
Grid[{{"Integral", "T", "T error", "M", "M error"}, {int, T, Terror, 
   M, Merror}}, Frame -> All]

I was hoping to simply declare a list: n={4,8,16}, but apparently that doesn't work. This kind of surprises me, because something like this would work:

g[x_] := x^2
mylist = {4, 8, 16}
g[mylist]
$\endgroup$
2
  • $\begingroup$ The simplest way probably would be to define everything as a function of n. $\endgroup$
    – Sumit
    Commented Dec 24, 2018 at 20:46
  • 1
    $\begingroup$ For a function to work with a List as an argument the same as if the function were mapped onto the List, the function must either 1) have the attribute Listable or 2) be composed of functions all of which are Listable. In your example, g acts as if it had the attribute Listable because its only component (Power) is Listable. $\endgroup$
    – Bob Hanlon
    Commented Dec 25, 2018 at 2:30

1 Answer 1

3
$\begingroup$
Clear["Global`*"]
xA := 0
xB := 2
f[t_] := 1 + t^2
int := Integrate[f[t], {t, xA, xB}] // N
h[n_] := (xB - xA)/n
xT[n_] := xA + h[n]*Range[0, n]
yT[n_] := f[xT[n]]
T[n_] := h[n] (Total[yT[n]] - 1/2 First[yT[n]] - 1/2 Last[yT[n]])//N
Terror[n_] := int - T[n]
xM[n_] := xA + h[n]*(Range[1, n] - 1/2)
yM[n_] := f[xM[n]]
M[n_] := Total[h[n]*f[xM[n]]] // N
Merror[n_] := int - M[n]
Grid[Join[{{"n", "Integral", "T", "T error", "M", "M error"}}, 
     Table[{n, int, T[n], Terror[n], M[n], Merror[n]}, {n, {4, 8, 16}}]],
     Frame -> All]

$ \begin{array}{cccccc} \text{n} & \text{Integral} & \text{T} & \text{T error} & \text{M} & \text{M error} \\ 4 & 4.66667 & 4.75 & -0.0833333 & 4.625 & 0.0416667 \\ 8 & 4.66667 & 4.6875 & -0.0208333 & 4.65625 & 0.0104167 \\ 16 & 4.66667 & 4.67188 & -0.00520833 & 4.66406 & 0.00260417 \\ \end{array} $

You can also Map them like

Map[Merror, {4, 8, 16}]

{0.0416667, 0.0104167, 0.00260417}

$\endgroup$

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.