Does R treat numbers mainly as double?
The following code suggests that R treats numbers as double. Even if I make it integer, it easily becomes double after some calculation. (Code1)
Also, even if the result looks like integer, interanlly it is treated as double. (Code2)
Is my understanding right?
Code 1:
> typeof(5)
[1] "double"
> typeof( 5 / 1 )
[1] "double"
> typeof( as.integer(c(1,2,3)) )
[1] "integer"
> typeof( as.integer(c(1,2,3)) + 1 )
[1] "double"
> typeof( as.integer(c(1,2,3)) / 1 )
[1] "double"
Code 2:
> 1 + 2
[1] 3
> typeof( 1 + 2)
[1] "double"
R handles numbers in different ways. In R both integers and double precision float defaults to their 32 bit version.
As pointed out by Andrey, there are two different types of numbers in R.
1L, 2L, 3L, ....
, this is equivalent to as.integer(1)
As well as their complex counterparts.
Literals are integers as such
typeof(1) #double
class(1) #numeric
typeof(1L) #integer
class(1L) #integer
is well defined. However upon calculation, if any part of the calculation is not stored as a lower or equal type than integer, it will automatically be converted to a double:
typeof(1L + 1L) #integer
typeof(1L + 1) #double
typeof(1L + TRUE) #integer
typeof(1L * 3) #double
typeof(1L * 3L) #integer
One should note however, as R runs with 32 bit variables, these have a limited range, compared to python 3.x. However one can get around the 32 bit variables ( in most cases! ) by using the packages bit64
for 64 bit integers and Rmpfr
which gives an interface for arbitrary floating point precision (according to their documentation).
I wrongly stated that "In R both integers and double precision float defaults to their 32 bit version". This is not the case for double precision variables, which default to a their 64 bit counterpart in almost all releases of R nowadays.