Re: [R] Comparing complex numbers

From: David Stoffer <dsstoffer_at_gmail.com>
Date: Fri, 11 Jul 2008 12:44:31 -0700 (PDT)

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.

______________________________________________
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.
Received on Fri 11 Jul 2008 - 19:48:59 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 11 Jul 2008 - 20:33:27 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive