[GiNaC-list] Floating to Rational

Vladimir V. Kisil V.Kisil at leeds.ac.uk
Wed Jul 19 11:42:37 CEST 2023


>>>>> On Tue, 18 Jul 2023 18:55:17 -1000, Charles White <whitece6 at hawaii.edu> said:

    CW> Hi GiNaC!  Is there a way to convert floating point numbers to
    CW> rational numbers? And, expressions with floating point numbers
    CW> to expressions with rational numbers? wxmaxima has the function
    CW> "rationalize"; I did notice there is a rationalize
    CW> <https://www.ginac.de/CLN/cln.html#Conversion-to-rational-numbers>
    CW> function in the CLN library; is that what I should work with?

    Yes, see the code below as an example.
    Probably, we can add something like that to the GiNaC itself if the
  maintainers see it meaningful.

  I am also wondering why do we not have a trivial constructor:
  numeric::numeric(cln::cl_N v) { value = v; }
  in the GiNaC?

  Best wishes,
  Vladimir
-- 
Vladimir V. Kisil                 http://www1.maths.leeds.ac.uk/~kisilv/
  Book:      Geometry of Mobius Maps       https://doi.org/10.1142/p835
  Soft:      Geometry of cycles         http://moebinv.sourceforge.net/
  Jupyter notebooks:        https://github.com/vvkisil?tab=repositories

==================================================
#include <iostream>
#include <ginac/ginac.h>
#include <cln/cln.h>
using namespace std;
using namespace GiNaC;

struct map_rationalize_ex : public map_function {
         ex operator()(const ex &e)
         {
			 if (is_a<numeric>(e)) {
				 cln::cl_N e_N =  ex_to<numeric>(e).to_cl_N();
				 cln::cl_RA e_R = rationalize(cln::realpart(e_N));
				 cln::cl_RA e_I = rationalize(cln::imagpart(e_N));
				 return numeric(cln::cl_I_to_long(numerator(e_R)), cln::cl_I_to_long(denominator(e_R)))
					 + I * numeric(cln::cl_I_to_long(numerator(e_I)), cln::cl_I_to_long(denominator(e_I)));
			 } else if (e.nops() > 0)
				 return e.map(*this);
			 else
				 return e;
		 }
};

int main()
{

	symbol x("x"), y("y");

	ex e = 0.5*sin((.6+I*.3)*x +exp(.25*y+.3333+I*numeric(1,7)))+pow(.4*x, .6);

	map_rationalize_ex rationalize_ex;

	cout << e << endl << "is rationalised to" << endl << rationalize_ex(e) << endl;
	
	return 0;
}


More information about the GiNaC-list mailing list