Created
March 22, 2021 22:58
-
-
Save soply/c8b74443a1919c99dcd187802f61af54 to your computer and use it in GitHub Desktop.
Computes Hermite coefficients of the tanh function using symbolic differentation (SymPy)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import sympy as sym | |
import time | |
def hermiteCoeffsTanh(nCoeffs): | |
""" | |
Computes the first nCoeffs Hermite coefficients of the tanh function. The r-th | |
Hermite coefficients is defined by | |
H_r(g) = int_{-oo}^{oo}g(y)h_r(y) * 1/sqrt(2 * pi) * exp(-x^2/2) dy | |
where h_r is the r-th normalized probablistic Hermite polynomial. | |
Params | |
----------------- | |
nCoeffs: number of Coefficients to return | |
Returns | |
----------------- | |
Hermite coefficients in a numpy array | |
# WARNING: Slow code! | |
""" | |
x = sym.symbols('x') | |
coeffs = np.zeros(nCoeffs) | |
gaussWeight = sym.exp((-x**2)/2) | |
fun = sym.tanh(x) | |
for i in range(nCoeffs): | |
t = time.time() | |
if i > 0: | |
der = sym.diff(der, x) | |
else: | |
der = fun | |
elapsed = time.time() - t | |
print(f"Computed {i}-th derivative in time : {elapsed}") | |
if i % 2 == 0: | |
coeffs[i] = 0.0 | |
print(f"{i}-th derivative has coefficient: {coeffs[i]}") | |
continue | |
t = time.time() | |
test = sym.integrate(sym.expand(der * 1/sym.sqrt(2 * sym.pi) * sym.exp(-sym.Rational(1,2) * (x**2))), (x, -sym.oo, sym.oo)) | |
coeffs[i] = 1.0/np.sqrt(np.math.factorial(i)) * float(test.n()) | |
elapsed = time.time() - t | |
print(f"{i}-th derivative has coefficient: {coeffs[i]}") | |
print(f"Used time: {elapsed}") | |
return coeffs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment