1 /* mpfr_reldiff -- compute relative difference of two floating-point numbers.
2
3 Copyright 2000-2001, 2004-2023 Free Software Foundation, Inc.
4 Contributed by the AriC and Caramba projects, INRIA.
5
6 This file is part of the GNU MPFR Library.
7
8 The GNU MPFR Library is free software; you can redistribute it and/or modify
9 it under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or (at your
11 option) any later version.
12
13 The GNU MPFR Library is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
16 License for more details.
17
18 You should have received a copy of the GNU Lesser General Public License
19 along with the GNU MPFR Library; see the file COPYING.LESSER. If not, see
20 https://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc.,
21 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */
22
23 #include "mpfr-impl.h"
24
25 /* reldiff(b, c) = abs(b-c)/b */
26 void
mpfr_reldiff(mpfr_ptr a,mpfr_srcptr b,mpfr_srcptr c,mpfr_rnd_t rnd_mode)27 mpfr_reldiff (mpfr_ptr a, mpfr_srcptr b, mpfr_srcptr c, mpfr_rnd_t rnd_mode)
28 {
29 mpfr_t b_copy;
30
31 if (MPFR_ARE_SINGULAR (b, c))
32 {
33 if (MPFR_IS_NAN (b) || MPFR_IS_INF (b) || MPFR_IS_NAN (c) ||
34 (MPFR_IS_ZERO (b) && MPFR_IS_ZERO (c)))
35 {
36 MPFR_SET_NAN (a);
37 return;
38 }
39 if (MPFR_IS_ZERO (b) || MPFR_IS_INF (c))
40 {
41 MPFR_SET_SAME_SIGN (a, b);
42 MPFR_SET_INF (a);
43 return;
44 }
45 /* The case c = 0 with b regular, which should give sign(b) exactly,
46 cannot be optimized here as it is documented in the MPFR manual
47 that this function just computes abs(b-c)/b using the precision
48 of a and the rounding mode rnd_mode for all operations. So let's
49 prefer the potentially "incorrect" result. Note that the correct
50 result is not necessarily better because if could break properties
51 (like monotonicity?) implied by the documentation. */
52 }
53
54 if (a == b)
55 {
56 mpfr_init2 (b_copy, MPFR_PREC(b));
57 mpfr_set (b_copy, b, MPFR_RNDN);
58 }
59
60 mpfr_sub (a, b, c, rnd_mode);
61 MPFR_SET_SIGN (a, 1);
62 mpfr_div (a, a, a == b ? b_copy : b, rnd_mode);
63
64 if (a == b)
65 mpfr_clear (b_copy);
66
67 }
68