← All challenges
mediumsympy/sympy · v1.5

Lambdify misinterprets some matrix expressions

Try this bug with AI

Fix it in the original repo with an AI agent and get feedback on how you worked.

2 free rounds each week

Round mode
  • Time limit60 min
  • Token budgetup to 1M
  • Worth up to210 XP
Sign up or sign in to start

Read the sample report

From a simulated Django round

You changed code before reproducing the bug.

Run the failing test before the first edit, so you know the failure you are fixing and can tell when it is gone.

Problem statement

Using lambdify on an expression containing an identity matrix gives us an unexpected result:

python
>>> import numpy as np
>>> n = symbols('n', integer=True)
>>> A = MatrixSymbol("A", n, n)
>>> a = np.array([[1, 2], [3, 4]])
>>> f = lambdify(A, A + Identity(n))
>>> f(a)
array([[1.+1.j, 2.+1.j],
       [3.+1.j, 4.+1.j]])

Instead, the output should be array([[2, 2], [3, 5]]), since we're adding an identity matrix to the array. Inspecting the globals and source code of f shows us why we get the result:

python
>>> import inspect
>>> print(inspect.getsource(f))
def _lambdifygenerated(A):
    return (I + A)
>>> f.__globals__['I']
1j

The code printer prints I, which is currently being interpreted as a Python built-in complex number. The printer should support printing identity matrices, and signal an error for unsupported expressions that might be misinterpreted.

The environment starts at commit f91de695585c (sympy/sympy 1.5), dependencies installed and tests runnable from the first minute. You are graded by hidden tests taken from the fix that was actually merged upstream.