Skip to content

Instantly share code, notes, and snippets.

@jcrudy
Created July 11, 2016 19:20
Show Gist options
  • Save jcrudy/0c2d7c9edeeba84aebc1299c0626157d to your computer and use it in GitHub Desktop.
Save jcrudy/0c2d7c9edeeba84aebc1299c0626157d to your computer and use it in GitHub Desktop.
from sympy import Symbol, Add, Mul, Max, RealNumber
from sympy.utilities.codegen import codegen
vars = {'x0': Symbol('x0'),
'x1': Symbol('x1')}
coefficients = [.5, 1.4, 9.8]
terms = [RealNumber(1), Max(0, Add(vars['x0'], RealNumber(-3.5))),
Mul(Max(RealNumber(0), Add(vars['x0'], RealNumber(-3.5))), Max(RealNumber(0), Add(vars['x1'], RealNumber(-6))))]
terms_with_coefs = [Mul(RealNumber(coef), term) for coef, term in zip(coefficients, terms) ]
expression = reduce(Add, terms_with_coefs)
print expression
print expression.subs(vars['x0'], 5.1).subs(vars['x1'],4.0).evalf()
(c_name, c_code), (h_name, h_code) = codegen(('f', expression), 'C')
print c_code
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment