SciProgCentre / kmath

Kotlin mathematics extensions library
651 stars 55 forks source link

Feature requests for BigInt #434

Open danwallach opened 2 years ago

danwallach commented 2 years ago

I'm looking at porting some code from java.math.BigInteger to use BigInt, and thus hopefully be multiplatform. Here are the missing features that would be handy:

altavir commented 2 years ago

Thank you very much for the issue. Can you clarify about ByteArray representation? Are there any specifications for it? Right now we use Int array for the magnitude so it is quite easy to dump it somewhere. I guess that in big-endian it will look the same for byte-based representation, but for little-endian, it will depend on the size of the chunk.

danwallach commented 2 years ago

Here's what java.math.BigInteger says for its toByteArray method:

Returns a byte array containing the two's-complement representation of this BigInteger. The byte array will be in big-endian byte-order: the most significant byte is in the zeroth element. The array will contain the minimum number of bytes required to represent this BigInteger, including at least one sign bit, which is (ceil((this.bitLength() + 1)/8)). (This representation is compatible with the (byte[]) constructor.)

Meanwhile, if you look at the gmpy Python front-end for GMP, it has functions like to_binary and from_binary with wildly unhelpful documentation:

to_binary(x) -> bytes Return a Python byte sequence that is a portable binary representation of a gmpy2 object x. The byte sequence can be passed to gmpy2.from_binary() to obtain an exact copy of x's value. Works with mpz, xmpz, mpq, mpfr, and mpc types. Raises TypeError if x is not a gmpy2 object.

And what exactly is this "portable" representation? So far as I can tell from here (https://gmplib.org/manual/I_002fO-of-Integers):

The integer is written in a portable format, with 4 bytes of size information, and that many bytes of limbs. Both the size and the limbs are written in decreasing significance order (i.e., in big-endian).

So, it would make some sense for kmath to work interchangeably with BigInteger, and perhaps to have some support for GMP.

altavir commented 2 years ago

Looks good. If you could make a PR, it would be quite welcome. Otherwise, I will return to this issue when I have a little bit more free time.

danwallach commented 2 years ago

I can't promise anything, but I'll see if I can work on it.