In R software
a <- 123456789123456789123456789
sprintf("%27f",a)
#[1] "123456789123456791337762816.000000"
I got the wrong answer. I want exact a
value.
Why is the system showing the wrong value of a
?
In R software
a <- 123456789123456789123456789
sprintf("%27f",a)
#[1] "123456789123456791337762816.000000"
I got the wrong answer. I want exact a
value.
Why is the system showing the wrong value of a
?
The reason you're not getting your exact value of a
is that R is storing it as a double instead of as an integer. Because a
is very large, there is some rounding that takes place when you assign a
.
Normally to store things as integers you would use L
at the end of the numbers; something like:
a <- 12L
class(a)
# [1] "integer"
However your number is too large for a standard integer in R, and you're forced to use the double representation:
a <- 123456789123456789123456789L
# Warning message:
# non-integer value 123456789123456789123456789L qualified with L; using numeric value
class(a)
# [1] "numeric"
You will need multiple precision to exactly store an integer this large. One option would be the gmp
package:
library(gmp)
a<-as.bigz("123456789123456789123456789")
a
# Big Integer ('bigz') :
# [1] 123456789123456789123456789
Other options for multi-precision arithmetic are available under the "Multi-Precision Arithmetic and Symbolic Mathematics" subheading of the numerical mathematics CRAN task view.
prod(as.bigz(c(2, 3, 7, 43, 1807, 3263443)))
–
Runway © 2022 - 2024 — McMap. All rights reserved.
gmp::as.bigz()
. – Wilbourn