diff --git a/.github/CHANGELOG.md b/.github/CHANGELOG.md index 8355042d5..2a2d3a1a6 100644 --- a/.github/CHANGELOG.md +++ b/.github/CHANGELOG.md @@ -13,6 +13,8 @@ * Recursive Torontonian added for faster computation based on paper ["Polynomial speedup in Torontonian calculation by a scalable recursive algorithm" by Ágoston Kaposi, Zoltán Kolarovszki, Tamás Kozsik, Zoltán Zimborás, and Péter Rakyta](https://arxiv.org/pdf/2109.04528.pdf). [#321](https://github.com/XanaduAI/thewalrus/pull/321) +* Hafnians of odd-sized matrices are calculated roughly twice as fast. [#329](https://github.com/XanaduAI/thewalrus/pull/329) + ### Bug fixes * Permanent algorithms handle 0x0 cases correctly. [#320](https://github.com/XanaduAI/thewalrus/pull/320) @@ -23,7 +25,7 @@ This release contains contributions from (in alphabetical order): -Jake Bulmer, Gregory Morse +Jake Bulmer, Gregory Morse, Nicolas Quesada --- diff --git a/thewalrus/_hafnian.py b/thewalrus/_hafnian.py index 2bd141db0..a1cb662d0 100644 --- a/thewalrus/_hafnian.py +++ b/thewalrus/_hafnian.py @@ -778,10 +778,6 @@ def hafnian( return np.prod(np.diag(A)) return 0 - if matshape[0] % 2 != 0 and loop: - A = np.pad(A, pad_width=((0, 1), (0, 1)), mode="constant") - A[-1, -1] = 1.0 - matshape = A.shape if matshape[0] == 2: @@ -789,6 +785,11 @@ def hafnian( return A[0, 1] + A[0, 0] * A[1, 1] return A[0][1] + if matshape[0] == 3 and loop: + return ( + A[0, 0] * A[1, 2] + A[1, 1] * A[0, 2] + A[2, 2] * A[0, 1] + A[0, 0] * A[1, 1] * A[2, 2] + ) + if matshape[0] == 4: if loop: result = (