garrettj403 / CZT

Chirp Z-Transform
MIT License
39 stars 14 forks source link

`iczt(X)` is numerical unstable and return nan when `len(X)` is too big (arround > 5000), fix suggestion included #17

Open mammalwong opened 1 month ago

mammalwong commented 1 month ago

version of czt: 0.0.7, issue was found when using google colab. To reproduce the issue:

import numpy as np
import czt as czt
for n in [1000,10000]:
  x = np.linspace(-4,4,n)
  y = np.exp(-x**2)
  yhat = czt.czt(y,simple=False)
  yphi = czt.iczt(yhat,simple=False)
  print(np.any(np.isnan(yhat)),np.any(np.isnan(yphi)))

outputs:

False False
False True

expected result:

False False
False False
mammalwong commented 1 month ago

suggested fix (tested in google colab locally) The np.cumprod call in the below lines of the source of iczt caused this numerical instability issue, it makes many tailing entries in p become 0:

    p = np.r_[1, (W ** k[1:] - 1).cumprod()]
    u = (-1) ** k * W ** (k * (k - n + 0.5) + (n / 2 - 0.5) * n) / p
    # equivalent to:
    # u = (-1) ** k * W ** ((2 * k ** 2 - (2 * n - 1) * k + n * (n - 1)) / 2) / p
    u /= p[::-1]

it can be solved by modifying the above few lines like this:

    u = (-1) ** k * W ** (k * (k - n + 0.5) + (n / 2 - 0.5) * n) # /p is removed from here (1)
    p = np.r_[1, W ** k[1:] - 1]
    lp = np.abs(p) # lp stand for ln(p)
    lp = np.cumsum(np.log(lp)) + np.angle(np.cumprod(p/lp))*1j
    # above seperate the magnitude and angle of the entries in p
    # it cumsum magnitude in log domain to replace the unstable cumprod of the magnitude
    # and cumprod only the normalized angle to ensure the angle is also stable when X is long
    u /= np.exp(lp+lp[::-1]) # /p from (1) is moved to here as +lp in exp()