Dear Ravi,
I suspect that, in general, you may be facing the limitations of machine
accuracy (more precisely, IEEE 754 arithmetics on [64-bit] doubles) in
your application. This is not a problem of R itself, but rather a
problem of standard arithmetics provided by underlying C compilers/CPUs.
In fact, every operation in IEEE arithmetics (so, this is not really a
problem only for complex numbers) may suffer from inexactness, a
particularly difficult one is addition/subtraction. Consider the
following example for real numbers (I know, it is not a very good one...):
The two functions
badfn <- function(x) 1-(1+x)*(1-x)
goodfn <- function(x) x^2
both calculate x^2 (theoretically, given perfect arithmetic). So, as you
want to allow the user to 'specify the mathematical function ... in
"any" form the user chooses', both functions should be ok.
But, unfortunately:
[1] 2.220446049250313e-16
[1] 1e-16
I don't know what happens in matlab/octave/scilab for this example. They
may do better, but probably at some cost (dropping IEEE arithmetic/do
"clever" calculations should result in massive speed penalties, try
evaluating hypergeom([1,-99.9],[-49.9-24.9*I],(1+1.71*I)/2); in
Maple...).
Now, you have some options:
- assume, that the user is aware of the numerical inexactness of ieee
arithmetics and that he is able to supply some "robust" version of the
mathematical function.
- use some other software (eg., matlab) for the critical calculations
(there is a R <-> Matlab interface, see package R.matlab on CRAN), if
you are sure, that this helps.
- implement/use multiple precision arithmetics within R (Martin
Maechler's Rmpfr package may be very useful:
http://r-forge.r-project.org/projects/rmpfr/ , but this will slow down
calculations considerably)
All in all, I think it is unfair just to blame R here. Of course, it
would be great if there was a simple trigger to turn on multiple
precision arithmetics in R. Packages such as Rmpfr may provide a good
step in this direction, since operator overloading via S4 classes allows
for easy code adaption. But Rmpfr is still declared "beta", and it
relies on some external library, which could be problematic on Windows
systems. Maybe someone else has other/better suggestions, but I do not
think that there is an easy solution for the "general" problem.
Best wishes,
Martin