Ask Your Question

Revision history [back]

[This is not really a full answer to your original question but the comment size limit prevents me from posting it as such.]

I don't quite see where the problem should be with the last example: The addition is performed in RDF, giving RDF(1.0) and only after that the conversion of RDF(1.0) to RF happens.

I'll try to explain what's happening as I understand it. First as a remark: The conversion of an element from RDF (53-bits of precision) to RF (RealField with 150-bits of precision) is of course non-canonical. In Sage terms: There is no coercion from RDF to RF, Sage will only automatically coerce from higher precision to lower.

By writing RF(RDF(0.7)) we explicitly ask Sage to convert a lower precision element of RDF to RF anyway, filling up the remaining digits in whatever way it sees fit. I guess this might be the confusing part, because this means that it is not (necessarily) true that RF(RDF(0.3) + RDF(0.7)) = RF(RDF(0.3)) + RF(RDF(0.7)).

If we do RF(0.3+0.7) this is the same as RF(RDF(0.3)+RDF(0.7)), thus the two numbers are added in RDF, giving RDF(1.0), and then converted to RF. If we do on the other hand RF(0.3) + RF(0.7) then 0.3 and 0.7 are interpreted as 150-bit numbers and added in RF (note that they are in fact parsed with the higher precision, they are not first stored as double elements and then converted). Finally and still different, RF(RDF(0.3))+RF(RDF(0.7)) will create the elements with 53-bit precision, then convert them to RF and add them there.

The documentation explains quite nicely how such coercion is performed in general. In particular the explain feature could be interesting for you:

sage: RF = RealField(150)
sage: cm = sage.structure.element.get_coercion_model()
sage: RF(0.3+0.7)
1.0000000000000000000000000000000000000000000
sage: cm.explain(0.3,0.7,add)
Identical parents, arithmetic performed immediately.
Result lives in Real Field with 53 bits of precision
Real Field with 53 bits of precision
sage: RF(RDF(0.3)+RDF(0.7))
1.0000000000000000000000000000000000000000000
sage: cm.explain(RDF(0.3),RDF(0.7),add)
Identical parents, arithmetic performed immediately.
Result lives in Real Double Field
Real Double Field
sage: RF(RDF(0.3)) + RF(RDF(0.3))
0.59999999999999997779553950749686919152736664
sage: cm.explain(RF(RDF(0.3)), RF(RDF(0.7)), add)
Identical parents, arithmetic performed immediately.
Result lives in Real Field with 150 bits of precision
Real Field with 150 bits of precision
sage: RF(0.3) + RDF(0.7)            
1.0
sage: cm.explain(RF(0.3), RDF(0.7), add)
Coercion on left operand via
    Native morphism:
      From: Real Field with 150 bits of precision
      To:   Real Double Field
Arithmetic performed after coercions.
Result lives in Real Double Field
Real Double Field

It may also be helpful to know that the arbitrary precision RealField you're using is implemented in sage/rings/real_mpfr.pyx and uses MPFR in the background.