Vincent Torri on Wed, 08 Jun 2005 14:09:27 +0200

[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: dumb question about rationals

On Wed, 8 Jun 2005, Bill Allombert wrote:

On Wed, Jun 08, 2005 at 07:20:23AM +0200, Vincent Torri wrote:


i've just started to use PARI (that is, the library), and I want to use
the rational objects. But I have some problems.
My program is quite simple :

   GEN r1;
   GEN r2;

   pari_init (1000000, 2);

   r1 = cgetg (3, t_FRAC);
   r2 = cgetg (3, t_FRAC);

   r1[1] = (long)2;
   r1[2] = (long)2;

   r2[1] = (long)2;
   r2[2] = (long)2;

   r2 = gadd (r2, r1);

but, when i launch the program, i get:

   ***   segmentation fault: bug in PARI or calling program.
   ***   Error in the PARI system. End of program.

Could you please tell me why there is this problem, and where my error(s)
is (are)

'r1[1] = (long)2;' is not correct, you must convert the C long integer 2 to a
PARI GEN integer using stoi().
'r1[1] = (long)stoi(2);' should work.

Secondly, the numerator and the denominator must be coprime else you
build a incorrect PARI object, so 2/2 is not allowed.

Usually it is simpler to use gdiv() to build rational numbers.

I suggest you try out GP2C. This program convert GP code to C code, so
you can use it to generate example code you can reuse.

For example, what you are doing is equivalent to the GP code

GP2C will translate it to the following C code:

 r1 = gdivgs(gdeux, 2);
 r2 = gdivgs(gdeux, 2);
 r2 = gadd(r1, r2);

Ok, thank you for your quick answer.

My aim is to construct rationals from any long. It seems that
 r = gdiv (stoi (l1), stoi (l2));
is working (l1 and l2 are long int).

In that case, should I construct r, that is, should I call cgetg ?
If no, what is the precision of the rational ? May i change it after this operation ?

Also, I've not well undestood the use of cgetg.

cgetg (N, t_FRAC) allocate a rational whose components (numerator and denominator) are coded on N*32 bits, right ?

In case that there is an overflow, does PARI increase the precision of the rational itself, or is there an error message (or something else) ?

I ask that because the computations I do lead to intermediate rationals with large coprime numerator and denominator (I don't know the limit of these numbers).

Thank you