1/* This example was presented at the CNC'2 summer school on MPFR and MPC at
2 * LORIA, Nancy, France. It shows how one can use different rounding modes.
3 * This example implements the OddRoundedAdd algorithm, which returns the
4 * sum z = x + y rounded-to-odd:
5 *   * RO(z) = z if z is exactly representable;
6 *   * otherwise RO(z) is the value among RD(z) and RU(z) whose
7 *     least significant bit is a one.
8 */
9
10/*
11Copyright 2009, 2010, 2011, 2012, 2013 Free Software Foundation, Inc.
12Contributed by the AriC and Caramel projects, INRIA.
13
14This file is part of the GNU MPFR Library.
15
16The GNU MPFR Library is free software; you can redistribute it and/or modify
17it under the terms of the GNU Lesser General Public License as published by
18the Free Software Foundation; either version 3 of the License, or (at your
19option) any later version.
20
21The GNU MPFR Library is distributed in the hope that it will be useful, but
22WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
23or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
24License for more details.
25
26You should have received a copy of the GNU Lesser General Public License
27along with the GNU MPFR Library; see the file COPYING.LESSER.  If not, see
28http://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc.,
2951 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
30*/
31
32#include <stdio.h>
33#include <stdlib.h>
34#include <gmp.h>
35#include <mpfr.h>
36
37#define LIST x, y, d, u, e, z
38
39int main (int argc, char **argv)
40{
41  mpfr_t LIST;
42  mpfr_prec_t prec;
43  int pprec;       /* will be prec - 1 for mpfr_printf */
44
45  if (argc != 4)
46    {
47      fprintf (stderr, "Usage: rndo-add <prec> <x> <y>\n");
48      exit (1);
49    }
50
51  prec = atoi (argv[1]);
52  if (prec < 2)
53    {
54      fprintf (stderr, "rndo-add: bad precision\n");
55      exit (1);
56    }
57  pprec = prec - 1;
58
59  mpfr_inits2 (prec, LIST, (mpfr_ptr) 0);
60
61  if (mpfr_set_str (x, argv[2], 0, MPFR_RNDN))
62    {
63      fprintf (stderr, "rndo-add: bad x value\n");
64      exit (1);
65    }
66  mpfr_printf ("x = %.*Rb\n", pprec, x);
67
68  if (mpfr_set_str (y, argv[3], 0, MPFR_RNDN))
69    {
70      fprintf (stderr, "rndo-add: bad y value\n");
71      exit (1);
72    }
73  mpfr_printf ("y = %.*Rb\n", pprec, y);
74
75  mpfr_add (d, x, y, MPFR_RNDD);
76  mpfr_printf ("d = %.*Rb\n", pprec, d);
77
78  mpfr_add (u, x, y, MPFR_RNDU);
79  mpfr_printf ("u = %.*Rb\n", pprec, u);
80
81  mpfr_add (e, d, u, MPFR_RNDN);
82  mpfr_div_2ui (e, e, 1, MPFR_RNDN);
83  mpfr_printf ("e = %.*Rb\n", pprec, e);
84
85  mpfr_sub (z, u, e, MPFR_RNDN);
86  mpfr_add (z, z, d, MPFR_RNDN);
87  mpfr_printf ("z = %.*Rb\n", pprec, z);
88
89  mpfr_clears (LIST, (mpfr_ptr) 0);
90  return 0;
91}
92