Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exactly storing large integers

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?

like image 399
aarthi Avatar asked Sep 03 '15 06:09

aarthi


People also ask

How do you store large integer values?

Below are the steps: Take the large number as input and store it in a string. Create an integer array arr[] of length same as the string size. Iterate over all characters (digits) of string str one by one and store that digits in the corresponding index of the array arr.

Which data type can store largest integer?

Longer integers: long The long data type stores integers like int , but gives a wider range of values at the cost of taking more memory. Long stores at least 32 bits, giving it a range of -2,147,483,648 to 2,147,483,647. Alternatively, use unsigned long for a range of 0 to 4,294,967,295.

What happens when you store a very large value in an int?

An integer overflow can cause the value to wrap and become negative, which violates the program's assumption and may lead to unexpected behavior (for example, 8-bit integer addition of 127 + 1 results in −128, a two's complement of 128).

How does python store big integers?

Practical Data Science using PythonPython supports a "bignum" integer type which can work with arbitrarily large numbers. In Python 2.5+, this type is called long and is separate from the int type, but the interpreter will automatically use whichever is more appropriate.


1 Answers

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.

like image 114
josliber Avatar answered Oct 04 '22 23:10

josliber