[R] Numbers that look equal, should be equal, but if() doesn'tsee as equal (repost with code included)

Simon Fear Simon.Fear at synequanon.com
Wed May 28 17:39:53 CEST 2003


Try the following function (the name is supposed to be a joke, by the
way),
which will also do the right thing with NAs and characters. Use it as
if(equal.enough(x,y)) rather than if(x==y), e.g.

> equal.enough(0.1+0.2, 0.3)
[1] TRUE

My default of 15 significant figures may be overkill in many
applications; be
prepared to reduce this.

Simon Fear


"equal.enough" <- function(x, y, sig.figs=15, d.p.zero=-Inf) {
# set argument d.p.zero to a real but small number (e.g. 1e-15) to
overide
# the sig.figs setting in favour of decimal places for comparison of
extremely small numbers
# (if appropriate - which is not always the case)
	if (is.numeric(x)) {
	  if (is.numeric(y)) {
	    if (is.infinite(d.p.zero))
		ifelse(is.na(x), is.na(y),
		ifelse(is.na(y), F,
		abs(signif(x, sig.figs) - signif(y, sig.figs)) == 0))
	    else
		ifelse(is.na(x), is.na(y),
		ifelse(is.na(y), F,
		abs(signif(x, sig.figs) - signif(y, sig.figs)) <=
d.p.zero))
	  } 
	  else is.na(y)		# a vector of F as long as y
	} else x==y
}
 

Simon Fear
Senior Statistician
Syne qua non Ltd
Tel: +44 (0) 1379 644449
Fax: +44 (0) 1379 644445
email: Simon.Fear at synequanon.com
web: http://www.synequanon.com
 
Number of attachments included with this message: 0
 
This message (and any associated files) is confidential and 
contains information which may be legally privileged.  It is 
intended for the stated addressee(s) only.  Access to this 
email by anyone else is unauthorised.  If you are not the 
intended addressee, any action taken (or not taken) in 
reliance on it, or any disclosure or copying of the contents of 
it is unauthorised and unlawful.  If you are not the addressee, 
please inform the sender immediately and delete the email 
from your system.

This message and any associated attachments have been 
checked for viruses using an internationally recognised virus 
detection process.  However, Internet communications cannot 
be guaranteed to be secure or error-free as information could 
be intercepted, corrupted, lost, destroyed, arrive late or 
incomplete. Therefore, we do not accept responsibility for any 
errors or omissions that are present in this message, or any 
attachment, that have arisen as a result of e-mail transmission.  
If verification is required, please request a hard-copy version. 
Any views or opinions presented are solely those of the author 
and do not necessarily represent those of Syne qua non.




More information about the R-help mailing list