MATLAB: Precise conversions from double to symbolic

doublesymbolic

I have the following number
r = 1.78503
I want to obtain the exact symbolic representation of 1/r, and I applied
p = 1/sym(r);
which gives me 1125899906842624/2009765110711289.
However, if I apply the form sym(1/r) then I got 2522982598259131/4503599627370496 which is different from the previous one. I understand this is due to the floating point numeric 1/r so the later form may not be accurate. Based on this observation, what measures should be taken in order to have exact values in a situation like this ? Is the form 1/sym(r) fully able to extract the exact symbolic representation here ? Thanks.

Best Answer

Compare:
r = 2.1234
sym(1/r)
1/sym(r)
1/sym(r,'d')
1/sym(r,'e')
1/sym(r,'f')
1/sym(r,'r')
s = sym(sprintf('%.16g', r));
feval(symengine,'numeric::rationalize',1/s,'Exact')
1/feval(symengine,'numeric::rationalize',s,'Exact')