Question

I am currently working on a Mathematica project to calculate Riemann's sums and put them in a table. I am having trouble printing the row numbers (intervals). (The row numbers are also parameters to the secondary functions). I don't know of any way to just access the index of the iterator in a Mathematica Table, so I am trying to compute them using the function parameters.

Here is an example of what I'd like to print, for the integral of x^2 over the range {0, 1}, with 10 subdivisions.

tableRiemannSums[#^2 &, {0, 1}, 10]

enter image description here

I need to figure out what the index of each iteration is, based on the value of the current subdivision k, the range of the integral {a, b}, and the number of subdivisions, n. Below is the main piece of code.

tableRiemannSums[fct_, {a_, b_}, n_] := Table[{'insert index here', 
leftRiemannSum[fct, {a, b}, 'insert index here'], 
rightRiemannSum[fct, {a, b}, 'insert index here']}, 
{k, a, b - (N[b - a]/n), N[b - a]/n}]

In the above equation, the line

{k, a, b - (N[b - a]/n), N[b - a]/n}]

means the range of the table is k as k goes from 'a' to 'b - ((b - a)/n)' in steps of size '(b - a)/n'.

In each of the places where my code says 'insert index here,' I need to put the same equation. Right now, I am using 'n * k + 1' to calculate the index, which is working for positive ranges, but breaks when I have a range like {a,b} = {-1, 1}.

I think this is a fairly straightforward algebra problem, but I have been racking my brain for hours and can't find a general equation.

(I apologize if this is a duplicate question - I tried searching through the Stack overflow archives, but had a hard time summarizing my question into a few key words.)

Was it helpful?

Solution

I finally figured out how to solve this. I was over thinking the range, rather than relying on the inner functions to control it. I rewrote the function as:

tableRiemannSums[fct_, {a_, b_}, n_] := Table[{k,
   leftRiemannSum[fct, {a, b}, k], 
   rightRiemannSum[fct, {a, b}, k]},
   {k, 1, n}}]

For reference, here are the left and right sums (for anyone interested!):

leftRiemannSum[fct_, {a_, b_}, n_] :=
 N[b - a]/n* Apply[Plus, Map[fct, Range[a, b - N[b - a] / n, N[b - a]/n]]]
rightRiemannSum[fct_, {a_, b_}, n_] := 
 N[b - a]/n* Apply[Plus, Map[fct, Range[a + (N[b - a]/n), b, N[b - a]/n]]]

OTHER TIPS

What you may want to consider is creating a function to make each line of the table. One argument to this function would be the row number.

Execute this function using MapIndexed, which will provide you a way to traverse your range as required while providing an incrementing row number.

(Create a list with the range of values, then apply your MapIndexed function to this list.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top