P2.7.6An integral of sine and cosine products
Write a function, sinm_cosn which returns the value of the following definite integral for integers \(m, n > 1\).
\[\begin{align*}
\int_0^{\pi/2} \sin^n\theta\cos^m\theta\;\mathrm{d}\theta = \left[
\begin{array}{ll}
\frac{(m-1)!!(n-1)!!}{(m+n)!!}\frac{\pi}{2} & \quad m,n \;\mathrm{both\;even,}\\
\frac{(m-1)!!(n-1)!!}{(m+n)!!} & \quad \mathrm{otherwise.}
\end{array}
\right.
\end{align*}\]
Hint: For calculating the double factorial, see Question Q2.4.6.
Show solution
Here is one possible solution.
import math
def double_factorial(n):
if not n % 2:
# Even n: n!! = 2**(n/2).(n/2)!
return 2**(n // 2) * math.factorial(n // 2)
# Odd n: n!! = 1.3.5...(n-2)n
dfactorial = 1
for i in range(3, n+1, 2):
dfactorial *= i
return dfactorial
def sinm_cosn(m, n):
""" Evaluate int_0^(pi/2) sin^m(x).cos^n(x) dx """
fac = double_factorial(m-1) * double_factorial(n-1) / double_factorial(m+n)
if m % 2 or n % 2:
return fac
return fac * math.pi / 2
for m in range(1,6):
for n in range(1,6):
print(n, m, sinm_cosn(m,n))