[R] Comparing complex numbers

Duncan Murdoch murdoch at stats.uwo.ca
Fri Jul 11 18:54:15 CEST 2008


On 7/11/2008 11:51 AM, David Stoffer wrote:
> Is there an easy way to compare complex numbers?
> 
> Here is a small example: 
> 
>>   (z1=polyroot(c(1,-.4,-.45)))
> [1]  1.111111-0i -2.000000+0i
>>   (z2=polyroot(c(1,1,.25)))
> [1] -2+0i -2+0i
>>   x=0
>>   if(any(identical(z1,z2))) x=99
>>    x
> [1] 0
> 
> #  real and imaginary parts:
> 
>>    Re(z1); Im(z1)
> [1]  1.111111     -2.000000
> [1] -8.4968e-21   8.4968e-21
> 
>>    Re(z2); Im(z2)
> [1] -2 -2
> [1]  0  0
> 
> Both z1 and z2 have a root of -2, but I guess Im(z1)
> isn't close enough to zero for identical().

== is the test you had in mind, I think, but like identical it requires 
exact equality.  identical() wants the whole vector to be identical. 
all.equal() checks for element by element approximate equality.

So you can get element by element approximate equality by something like

 > for (i in 1:length(z1)) print(all.equal(z1[i], z2[i]))
[1] "Mean relative Mod difference: 2.8"
[1] TRUE

The trouble with this approach is that it will use a different scale for 
each comparison.  I think you really need to fashion your own test, e.g.

 > abs(z1-z2) < 1e-15
[1] FALSE  TRUE

Duncan Murdoch



More information about the R-help mailing list