1

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

Manuel Oliveira
  • 527
  • 5
  • 19

1 Answers1

2

You could take a similar approach as in your previous question: subclass the code generator and overwrite _print_Rational(). Custom user_functions can be added via the settings= parameter:

import sympy as sp
from sympy.printing.c import C99CodePrinter

class CustomCodePrinter(C99CodePrinter):
    def _print_Rational(self, expr):
        return str(sp.N(expr))

my_user_functions = {"cos": "my_fast_cos"}

custom_ccode = CustomCodePrinter(settings={'user_functions': my_user_functions}).doprint
print(custom_ccode(sp.Rational(1, 7) + sp.cos(sp.Rational(1, 3))))
JohanC
  • 71,591
  • 8
  • 33
  • 66
  • This is actually good for this case! Anyway to also pass `user_functions` in the `CustomCodePrinter`? I am getting the following error: `TypeError: doprint() got an unexpected keyword argument 'user_functions'` – Manuel Oliveira Jan 06 '21 at 10:25