0

I'm trying to get sympy to convert some formulas into code in a language almost identical to C. However this language needs float literals to have the 'f' at the end other wise it promotes it to a double. Even when sympy is provided a literal that is explicitly typed as a 32bit float it doesn't do this. How do I make it do this?

notes:

  1. I'm using C99CodePrinter directly in my example because I'm subclassing it.
  2. target language is opencl, which is why we are using floats instead of doubles (some GPUs don't support doubles)

here is a minimal example:

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

myPrinter = C99CodePrinter()

x = sp.symbols('x')
y = np.ones(1,dtype=np.float32)
print(myPrinter.doprint(y[0]*x))

I was expecting to get "1.0f*x" but I actually get "1.0*x"

p . clark
  • 21
  • 2

1 Answers1

2

so answering my own question here. the correct minimal example would have been

import sympy as sp
from sympy.printing.c import C99CodePrinter
from sympy.codegen.ast import real, float32
import numpy as np

myPrinter = C99CodePrinter(settings={"type_aliases":{real: float32}})

x = sp.symbols('x')
y = np.ones(1,dtype=np.float32)
print(myPrinter.doprint(y[0]*x))

seems like the printer defaults to assuming every real number is float64 unless its overridden as shown.

p . clark
  • 21
  • 2