Ruud H.G. van Tol on Thu, 05 Jun 2025 10:26:10 +0200


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

Re: ran 3 trials of 100K to check the recovery of a rational number from its decimal



On 2025-06-05 08:05, American Citizen wrote:

And somewhat irritatingly, I got a zero from the random(N) function call, which resulted in a zero in the denominator, so I had to watch out for that.

That is how random() generally works, in most of the environments I use, so check the documentation:

?? random

random({N = 2^31}):

   Returns a random element in various natural sets depending on the argument N.

* t_INT: let n = |N|-1; if N > 0 returns an integer uniformly distributed in [0, n]; if N < 0 returns an integer uniformly distributed in [-n, n]. Omitting the argument is equivalent to random(2^31).

* t_REAL: returns a real number in [0,1[ with the same accuracy as N (whose mantissa has the same number of significant words).
[...]

-- Ruud

Code variant:

{
my(N=10^30);
localprec(77);
for(s=1, 10,
  my(n=1+random(N-1), d=1+random(N-1), a=n/d, b=1.0*a);
  b= contfracpnqn( contfrac(b) );
  b= b[1,1] / b[2,1];
  print("trial1: ", a-b);
);
}