Skip to content

[kalman] One comment on the code #894

Closed

Description

@longye-tian

Hi @jstac

I had a code-related question in the first Kalman filter lecture.

The exercise asks readers to compare

$$ | x_t - A x_{t-1} |^2 $$

with

$$ | x_t - \hat x_t |^2, $$

where $\hat x_t$ is the Kalman filter prediction of $x_t$.

In the solution, the loop currently does

for t in range(1, T):
    kn.update(y[:,t])
    diff1 = x[:, t] - kn.x_hat.flatten()
    diff2 = x[:, t] - A @ x[:, t-1]

The reason I am worried about the timing is that Kalman.update(y) appears to call both prior_to_filtered(y) and filtered_to_forecast(), according to the QuantEcon documentation:

def update(self, y):
        """
        Updates x_hat and Sigma given k x 1 ndarray y.  The full
        update, from one period to the next

        Parameters
        ----------
        y : np.ndarray
            A k x 1 ndarray y representing the current measurement

        """
        self.prior_to_filtered(y)
        self.filtered_to_forecast()

Since filtered_to_forecast() advances the filtering distribution to the next predictive distribution, kn.x_hat after kn.update(y[:, t]) seems to represent the next prior rather than the prediction being compared with $x_t$.

If that is right, then diff1 is comparing $x_t$ with a one-period-ahead object.

Would it be more consistent with the exercise to update the filter using the previous observation before comparing with $x_t$, e.g.

for t in range(1, T):
    kn.update(y[:, t-1])
    diff1 = x[:, t] - kn.x_hat.flatten()
    diff2 = x[:, t] - A @ x[:, t-1]

Then both errors are comparing predictions of $x_t$.

What do you think? I can put up a PR if this interpretation is correct.

Best,
Longye

Activity

  1. jstac commented on Jun 6, 2026

    @jstac
    Contributor

    Hi @longye-tian , good catch! Yes, please put up a PR with a fix.

    Much appreciated!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions