I am trying to generate C code with sympy, through the function ccode.
Currently, I am trying to convert sympy's Rational numbers to floats for faster computation.
As an example I have:
import sympy as sp
x=sp.Symbol('x')
y=sp.Symbol('y')
d=sp.Symbol('d')
test=sp.Matrix([
[x/3 + y + 2*d/3, 0, 0],
[0, x/3 + y + 2*d/3, 0],
[0, 0, x/3 + y - 2*d/3]])
res = sp.cse(test)
lines = []
for i, result in enumerate(res):
lines.append(sp.ccode(result,"result_%i"%i, user_functions={'Mul':[(lambda x: x.args[0].is_Rational, lambda x: sp.N(x,n=17))]}))
If the matrix part of res
had a fraction (res[1]
), I could just loop over it with a for loop and a try/except statement:
for i in range(len(res[1])):
try:
res[1][i].args[0].is_Rational
except:
continue
else:
res[1][i]=sp.N(res[0][i],n=20)
and change the rational values to floating point with the function sp.N
.
However, I am having difficulty to define a lambda function/any other function to do this to the list of tuples in res[0]
.
Would appreciate some help!
Kind Regards