4

If I evaluate the following code

t = Developer`ToPackedArray[{0, 2/7, -(1/7)}];
Developer`PackedArrayQ[t]

Mathematica returns False.

Is there any way that I can pack an array of rational numbers?

Gert
  • 1,530
  • 8
  • 22
  • 2
    No, packed arrays can obly be used for machine precision reals (64 bit floats, a.k.a. doubles), _machine precision complex numbers, and for _machine integers (64 bit integers). – Henrik Schumacher Nov 18 '20 at 16:02
  • 4
    You can't. See the docs - it says Possible types are: Integer, Real, and Complex. . FullForm[2/7] is Rational[2,7] so it won't work. You either use reals / complex (machine) numbers, or you have two lists of integers, one for the numerator, one for the denominator, or have a list of pairs of integers. – flinty Nov 18 '20 at 16:02
  • Ow, I couldn't find the docs on packedarray because I looked for Packed Array in the documentation center and it only returned some info about packed array as a datatype for compiled functions. Thank you very much. – Gert Nov 18 '20 at 16:19

1 Answers1

6

You can't. See the docs - it says Possible types are: Integer, Real, and Complex. If you check FullForm[2/7] it gives Rational[2,7] so it won't work.

So you either use reals / complex (machine) numbers, or you have two lists of integers, one for the numerator, one for the denominator, or have a list of pairs of integers.


Here's how you can pack a list of pairs of {numerator, denominator} instead since you are allowed to pack integers:

t = Developer`ToPackedArray[NumeratorDenominator[{0, 2/7, -(1/7)}]]
Developer`PackedArrayQ[t]
(* True *)
flinty
  • 25,147
  • 2
  • 20
  • 86
  • Bear in mind: Only machine-sized numbers can be stored in packed form so I think there will be a limit on how large a magnitude those numerators/denominators can have. – flinty Nov 18 '20 at 16:07
  • ... and that will be any number allowed from min -2^63 to max 2^63 - 1 apparently (on a 64 bit machine). – flinty Nov 18 '20 at 16:13
  • If you could add the comment (it can't be done) to your answer I will mark it as correct. – Gert Nov 18 '20 at 16:21