2

I'm currently trying to introduce myself to some programming with Mathematica. I'm not the most familiar with programming in general, but I work best by just trying to make stuff.

In this code, I'm trying to make a Riemann sum. I know that the Riemann sum function exists, but I want to try to make it myself. So far here is what I have.

 taylorintegral[Demand_, Lower_, Upper_] := 
   Module[{x},
     Δxintegral = (Upper - Lower)/n;
     xistar = Lower + Δxintegral*i;
     Limit[Sum[Demand[xistar]*Δxintegral, {i, 1, n}], n -> ∞]]

Now, if I say run the following

taylorintegral[x^2, 1, 3]

The output I receive is,

Limit[Sum[(2*(x^2)[1 + (2*i)/n])/n, {i, 1, n}], n -> Infinity]

Where it didn't actually plug in the xistar value in for x^2.

How do I define the module so that it reads the demanded function and then evaluates the demanded function at xistar within the Limit[Sum[...]] code?

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
  • It doesn't work because x^2 is not a function and therefore can't take anything as input. You can input a pure function to your function like this: taylorintegral[#^2 &, 1, 3] – Anjan Kumar May 11 '17 at 01:16
  • 2
    I'm voting to close this question as off-topic because it is too localized; i.e, it applies only to the local situation and needs of its poster and answers will not benefit others. – m_goldberg May 11 '17 at 02:15

1 Answers1

2

You got both the math and the Mathematica syntax wrong. Here is a corrected version of your code.

myIntegrate[expr_, var_Symbol, low_?NumericQ, high_?NumericQ] :=
  Module[{Δx, n},
    Δx = (high - low)/n;
    Limit[Δx Sum[expr /. var -> i, {i, low, high, Δx}], n -> ∞]]
myIntegrate[x^2, x, 1, 3]

26/3

But this way of forming the Riemann sum is very inefficient. The performance is very bad for anything other than simple polynomials.

Note: Module is for localizing variables; i.e., for limiting the scope of variables that only appear inside the module.

m_goldberg
  • 107,779
  • 16
  • 103
  • 257