简体   繁体   中英

Using sympy cxxcode on Heaviside function fails

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))

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)))'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM