Skip to content

Instantly share code, notes, and snippets.

@9999years
Last active December 11, 2016 07:16
Show Gist options
  • Save 9999years/fc334cdd38c810ba51959bf90178415f to your computer and use it in GitHub Desktop.
Save 9999years/fc334cdd38c810ba51959bf90178415f to your computer and use it in GitHub Desktop.
Maxima functions for approximating integrals
/* functions for trapezoidal, midpoint, and
* right/left endpoint approximations of integrals
* arguments:
* f(t): function to be approximated
* t: dependent variable of f(t)
* bottom: bottom limit of integration
* top: top limit of integration
* n: number of samples/slices to be used in approximation
*/
trapezoidal(f, t, bottom, top, n) := block(
[f: f, t: t, bottom: bottom, top: top, n: n, Δt],
Δt: (top - bottom) / n,
define(g(t), f),
x(i) := block([i: i], bottom + i * Δt),
ratsimp((Δt/2)*(g(x(0)) + 2 * sum(g(x(i)), i, 1, n - 1) + g(x(n))))
);
midpoint(f, t, bottom, top, n) := block(
[f: f, t: t, bottom: bottom, top: top, n: n, Δt],
Δt: (top - bottom) / n,
define(g(t), f),
x(i) := block([i: i], bottom + ((2 * i - 1) / 2) * Δt),
ratsimp(Δt * sum(g(x(i)), i, 1, n))
);
leftendpoint(f, t, bottom, top, n) := block(
[f: f, t: t, bottom: bottom, top: top, n: n, Δt],
Δt: (top - bottom) / n,
define(g(t), f),
x(i) := block([i: i], bottom + i * Δt),
ratsimp(Δt * sum(g(x(i)), i, 0, n - 1))
);
rightendpoint(f, t, bottom, top, n) := block(
[f: f, t: t, bottom: bottom, top: top, n: n, Δt],
Δt: (top - bottom) / n,
define(g(t), f),
x(i) := block([i: i], bottom + i * Δt),
ratsimp(Δt * sum(g(x(i)), i, 1, n))
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment