[R] Comparing complex numbers
David Stoffer
dsstoffer at gmail.com
Fri Jul 11 21:44:31 CEST 2008
Thanks- I was hoping I wouldn't have to loop, but using abs() is better than
comparing Re()s and Im()s, which was my original thought. I have to compare
all the roots, so I used something like this:
> for (i in 1:length(z1)) if(any(abs(z1[i]-z2[1:length(z2)])<1e-15))
> print("ouch")
... thanks again for your help.
Duncan Murdoch-2 wrote:
>
> 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
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
>
-----
The power of accurate observation is commonly called cynicism
by those who have not got it. George Bernard Shaw
--
View this message in context: http://www.nabble.com/Comparing-complex-numbers-tp18406924p18411302.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list