Skip to content

Instantly share code, notes, and snippets.

@mskashi
Created January 28, 2020 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mskashi/b0f254d21a195111e1a7ead9db7c0c18 to your computer and use it in GitHub Desktop.
Save mskashi/b0f254d21a195111e1a7ead9db7c0c18 to your computer and use it in GitHub Desktop.
# calculate coefficients of Newton-Cotes integral formula
# for \int_a^b f(x)dx
# using sampling points x0(=a), x1, ..., xn-1, xn(=b)
import sympy as sym
n = 7;
x = sym.Symbol('x');
a = sym.Symbol('a');
b = sym.Symbol('b');
h = (b - a) / n;
lx = [0] * (n+1);
for i in range(0,n+1):
lx[i] = a + i * h;
for i in range(0,n+1):
tmp = 1
for j in range(0,n+1):
if j != i:
tmp *= (x - lx[j]);
tmp /= (lx[i] - lx[j]);
result = sym.simplify(sym.integrate(tmp, (x, a, b)));
print("(b - a) * " + str(sym.simplify(result / (b - a))) + " * f(x" + str(i) + ")");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment