Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Difference between ComplexField and MPComplexField?

Hi everyone. I'm a long-time SAGE user, a little over a decade off and on. I have a variety of interests, but most of my coding time is spent working with matrix LU decompositions, finding Taylor series of "elementary" complex functions (logarithm or algebraic roots, e.g., log(x-c) or (x-c)^(2*pi*I/a), where c and a are complex numbers). And for years, I've been using the RealField and ComplexField classes, with their corresponding RealNumber and ComplexNumber elements, as the backbone of my code.

Just today, I discovered the MPComplexField class. I've been writing my own cython modules, borrowing code from the sage/rings/real_mpfr.pyx file. I noticed somewhere in my boilerplate code, that I was importing the MPC library. The MPC library appears to just be a C wrapper around the MPFR library, to perform complex arithmetic using pairs of MPFR numbers.

This struck me as a bit odd, because I've casually read through the source code in sage/rings/complex_number.pyx, and it looks to me like all the complex math is coded manually. E.g.,

a+b is calculated as ( + + I*( + a*b is calculated as (* -* + I*(* +* sin(a) is a horrendous calculation involving sinh, square root, sine and cosine, as well as basic operations like multiplication, squaring, etc. (Yes, I paraphrased the mpfr_xxx calls to make them readable.)

In other words, the ComplexNumber class implements the complex calculations manually, whereas the MPComplexNumber class lets the library handle those calculations. Calculating sin(a) is just a call to mpc_sin().

Which leads to my question. Why the two different classes? Which one is preferred as the more SAGE-ish approach? Is there a long-term plan to switch to MPC as the default in tutorials and code examples?

I ran some simple tests, and it appears that the rounding is not the same, at least not with default settings. After a few simple arithmetic calculations, I get diverging results, which I can only assume is due to a difference in rounding, and possibly due to differing internal algorithms. I've been using the ComplexField for over a decade, so I'm hesitant to switch. But I'm wondering if the MPComplexNumber has either better performance or better rounding, at least for most common applications.

Sorry for the long post, but this MPComplexNumber class appears to have been in SAGE for quite some time (since 2008). It seems like it must be the red-headed stepchild, because I don't seem to see it get mentioned anywhere. But if the performance is better, I'd gladly make the switch in all my coding projects. Any insight or advice?

Edit: My asterisk got turned into italics, which messed up my math sections. Escaped the asterisks, hope that fixes it.