QofNumeric Example

EXAMPLE

The following program finds the best QofNumeric approximation to the math.h constant M_PI given a maximum denominator. For large denominators, the QofNumeric approximation is accurate to more decimal places than will generally be needed, but in some cases this may not be good enough. For example,

    M_PI                   = 3.14159265358979323846
    245850922 / 78256779   = 3.14159265358979311599  (16 sig figs)
    3126535 / 995207       = 3.14159265358865047446  (12 sig figs)
    355 / 113              = 3.14159292035398252096  (7 sig figs)

#include <glib.h>
#include <qof.h>
#include <math.h>

int
main(int argc, char ** argv)
{
  QofNumeric approx, best;
  gdouble err, best_err=1.0;
  gdouble m_pi = M_PI;
  gint64 denom;
  gint64 max;

  sscanf(argv[1], "%Ld", &max);
  
  for (denom = 1; denom < max; denom++)
  {
    approx = qof_numeric_from_double (m_pi, denom, GNC_RND_ROUND);
    err    = m_pi - qof_numeric_to_double (approx);
    if (fabs (err) < fabs (best_err))
    {
      best = approx;
      best_err = err;
      printf ("%Ld / %Ld = %.30f\n", qof_numeric_num (best),
              qof_numeric_denom (best), qof_numeric_to_double (best));
    }
  }
}

Generated on Thu Jan 31 22:50:27 2008 for QOF by  doxygen 1.5.4