Alexandre Hoffmann
Alexandre Hoffmann

Reputation: 341

Code generation - custom floating point type

I'm using sympy to generate c++ that evaluate a polynomial whose coefficients are expressed as fractions of very large integers.

I would like to use MPFR to represent theses coefficients.

Is it possible to make sympy write my expressions as :

mpreal("3556524138052763")/mpreal("533531142144000") - mpreal("4492451542803491")/mpreal("6402373705728000")*eta

Instead of

3556524138052763.0/533531142144000.0 - 4492451542803491.0/6402373705728000.0*eta

Upvotes: 0

Views: 46

Answers (2)

smichr
smichr

Reputation: 18929

I'm not sure how this will be "written" but if you define a Function mpreal you can use that to wrap the numerator and denoninator of Rationals while excluding Integers:

>>> from sympy import Function
>>> from sympy.abc import x, y
>>> f=Function('mpreal')
>>> (x/2+3*y).replace(
... lambda x: x.is_Rational and not x.is_Integer,
... lambda x: f(x.p)/f(x.q))
.. 
x*mpreal(1)/mpreal(2) + 3*y

Upvotes: 1

Pavel Holoborodko
Pavel Holoborodko

Reputation: 557

Yes, it is Ok. But don't forget to set the precision in generated C++ code:

mpfr::mpreal::set_default_prec(...);

Upvotes: 0

Related Questions