Код: Выделить всё
import numpy as np
def trap_1D(func, a, b, N, *args):
#Computes the integral of a univariate function over [a, b] using the composite trapezoidal rule.
h = (b - a) / N #The grid spacing
x = np.linspace(a, b, N + 1) #The sub-division points: x_0, x_1,...,x_N.
y = func(x, *args)
return (np.sum(y) - (y[0] + y[-1]) / 2) * h
Код: Выделить всё
def create_I(f, a, b, N):
def I(x):
return trap_1D(lambda y: f(x, y), a, b, N) #integrate the function y --> f(x,y)
return I
Код: Выделить всё
def f(x,y):
return np.sin(x)*np.cos(y)
N = 100
I = create_I(f, 0.0, np.pi/2, N) #The function I() is correct
I2 = trap_1D(I, 0.0, np.pi/2, N) #This gives an error
Код: Выделить всё
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_15880\410820249.py in
26 N = 100
27 I = create_I(f, 0.0, np.pi/2, 100)
---> 28 trap_1D(I, 0.0, np.pi/2, N)
~\AppData\Local\Temp\ipykernel_15880\410820249.py in trap_1D(func, a, b, N, *args)
9 y = func(x, *args)
10
---> 11 return (np.sum(y) - (y[0] + y[-1]) / 2) * h
12
13
IndexError: invalid index to scalar variable.
Подробнее здесь: https://stackoverflow.com/questions/792 ... oidal-rule