Skip to content

Undocumented bahavior of as.integer() (PR#2430)

2 messages · Martin Maechler, Duncan Murdoch

#
PhGr> as.integer() truncates doubles toward zero, as Splus
    PhGr> does (at least v. 6.1 under Windows does). Thus:

(fortunately this is not OS dependent!)

    >> look <- (10 * seq(14)) - 76
    >> 10 * (73.1 + look)
    PhGr>[1] 71 171  271  371  491  586  681  791  886  981 1101 1201 1301 1401
    >> as.integer(10 * (73.1 + look))
    PhGr>[1] 70 170  270  370  490  586  681  791  886  981 1101 1201 1301 1401

    PhGr> ... It is not documented in R! I propose appending the following to
    PhGr> as.integer.Rd:

I agree the doc should mention it.
I disagree with the warning section.
In R, our code really just uses something like

   int asInt(double x) { return x; }

which makes use of C's  "implicit casting".  
I know looked in Kernighan & Ritchie (2nd Ed.; {3rd Ed would be better})
and found (p.197)

   >>  "A6.3 Integer and Floating"
   >>  
   >>  When a value of floating type is converted to integral type,
   >>  the fractional part is discarded. ...................

Hence this is (fortunately!) part of the C standard.
But I really think any decent programming language would do it
like that (many would not allow implicit coercion though..).
That's the reason I think the warning is not necessary; I'd
rather mention it by the way.

    PhGr> \section{ WARNING }{ During coercion of doubles, real
    PhGr> numbers are not rounded but truncated (the closest
    PhGr> integer towards zero is returned).  Attributes are
    PhGr> deleted.}

    PhGr> And I suggest adding the previous exemple in the
    PhGr> corresponding section in as.integer.Rd. Moreover, the
    PhGr> subset operation [] uses as.integer() and
    PhGr> consequently, can suffer from the same syndrome. A
    PhGr> WARNING section in Extract.Rd would be welcome too.

"suffer" and "syndrome"  are not appropriate here IMHO.

Martin Maechler <maechler@stat.math.ethz.ch>	http://stat.ethz.ch/~maechler/
Seminar fuer Statistik, ETH-Zentrum  LEO C16	Leonhardstr. 27
ETH (Federal Inst. Technology)	8092 Zurich	SWITZERLAND
phone: x-41-1-632-3408		fax: ...-1228			<><
#
On Wed, 8 Jan 2003 11:51:22 +0100 (MET), you wrote:

            
The dialects of Pascal that I use are pretty decent, but they don't
allow casting of floats to integers because of this ambiguity.  You
need to say round() or trunc() explicitly.  I'd think any decent
programming language would do that :-)

Duncan Murdoch