[Top][All Lists]

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

Re: ratio implementation

From: Marius Vollmer
Subject: Re: ratio implementation
Date: Fri, 17 Oct 2003 12:09:02 +0200
User-agent: Gnus/5.1003 (Gnus v5.10.3) Emacs/21.3 (gnu/linux)

Kevin Ryde <address@hidden> writes:

> Marius Vollmer <address@hidden> writes:
>> I don't have the details ready yet, but I think I'll try to come up
>> with code for this... (when it isn't already in GMP).
> gmp has an mpq_set_d, which does what you imagine, extract the bits to
> make a binary fraction.  The actual implementation is uglified by the
> details of gmp internals though.

Yes, that's what I was looking for.  I now have in scm_inexact_to_exact

  else if (SCM_REALP (z))
      mpq_t frac;
      SCM q;
      mpq_init (frac);
      mpq_set_d (frac, SCM_REAL_VALUE (z));
      q = scm_make_ratio (scm_i_mpz2num (mpq_numref (frac)),
                          scm_i_mpz2num (mpq_denref (frac)));
      mpq_clear (frac);
      return q;

using the helper

    scm_i_mpz2num (mpz_t b)
      /* convert a mpz number to a SCM number. */
      if (mpz_fits_slong_p (b))
          long val = mpz_get_si (b);
          if (SCM_FIXABLE (val))
            return SCM_MAKINUM (val);

        SCM z = scm_double_cell (scm_tc16_big, 0, 0, 0);
        mpz_init_set (SCM_I_BIG_MPZ (z), b);
        return z;

Kevin, does this look OK from a GMP point of view?  I.e., no memory
leaks, etc?

That code gives perfect accuracy but that can be strange as well:

    guile> (exact->inexact 1/1000)
    guile> (inexact->exact (exact->inexact 1/1000))
    guile> (rationalize (exact->inexact 1/1000) 1e-16)

The above behavior of inexact->exact better fits R5RS, I'd say, since
R5RS calls for the _closest_ representable exact number, not for the
simplest, as with rationalize.  So I'm inclined to use it intead of
rationalize.  Ok?

reply via email to

[Prev in Thread] Current Thread [Next in Thread]