Skip to content Skip to sidebar Skip to footer

Numerical Integration Methods Question Python

I am trying to integrate the following formula: Below is my attempt to perform this integration using a homemade scheme for f(a) = sin(a). def func(x): return math.sin(x) def

Solution 1:

It seems that your problem is the math.sin function, which doesn't support complex arguments:

i = np.exp(.5j * np.pi)
math.sin(i), np.sin(i)
(6.123233995736766e-17, (9.44864380126377e-17+1.1752011936438014j))

It also throws a warning (but not an error...):

ComplexWarning: Casting complex values to real discards the imaginary part

Using np.sin instead fixes the problem.

In general, the implementation might be simpler to express (and easier to debug) with more use of numpy, like

def integration(func, a, n, r, n_steps):
    z = r * np.exp(2j * np.pi * np.arange(0, 1, 1. / n_steps))
    return math.factorial(n) * np.mean(func(a + z) / z**n)

np.allclose(1., integration(np.sin, a=0., n=1, r=1., n_steps=100))

True

Post a Comment for "Numerical Integration Methods Question Python"