Home > Blockchain >  Using sympy cxxcode on Heaviside function fails
Using sympy cxxcode on Heaviside function fails

Time:07-13

I am using sympy version 1.10.1 and numpy version 1.20.0. Can someone please explain why the following simple code results in an error?

import sympy as sp
from sympy.printing import cxxcode

T = sp.symbols('T', real=True, finite=True)
func = sp.Heaviside(T - 0.01)
func_cxx = cxxcode(func)

The error is

ValueError: All Piecewise expressions must contain an (expr, True) statement to be used as a default condition. Without one, the generated expression may not evaluate to anything under some condition.

I understand that sympy converts Heaviside to a Piecewise function, but I'd imagine the corresponding Piecewise is also defined for all real & finite T:

>>func.rewrite(sp.Piecewise)
>>Piecewise((0, T - 0.01 < 0), (1/2, Eq(T - 0.01, 0)), (1, T - 0.01 > 0))

CodePudding user response:

If I were you I would open an issue on SymPy.

To solve your problem you might want to modify the function in order to get cxxcode to work:

func = func.rewrite(Piecewise)
# modify the last argument to insert the True condition
args = list(func.args)
args[-1] = [args[-1][0], True]
# recreate the function
func = Piecewise(*args)
print(cxxcode(func))
# out: '((T - 0.01 < 0) ? (\n   0\n)\n: ((T - 0.01 == 0) ? (\n   1.0/2.0\n)\n: (\n   1\n)))'
  • Related