1 /* Test mpq_cmp.
2 
3 Copyright 1996, 2001 Free Software Foundation, Inc.
4 
5 This file is part of the GNU MP Library test suite.
6 
7 The GNU MP Library test suite is free software; you can redistribute it
8 and/or modify it under the terms of the GNU General Public License as
9 published by the Free Software Foundation; either version 3 of the License,
10 or (at your option) any later version.
11 
12 The GNU MP Library test suite is distributed in the hope that it will be
13 useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
15 Public License for more details.
16 
17 You should have received a copy of the GNU General Public License along with
18 the GNU MP Library test suite.  If not, see https://www.gnu.org/licenses/.  */
19 
20 #include <stdio.h>
21 #include <stdlib.h>
22 
23 #include "gmp-impl.h"
24 #include "tests.h"
25 
26 #define SGN(x) ((x) < 0 ? -1 : (x) > 0 ? 1 : 0)
27 
28 int
ref_mpq_cmp(mpq_t a,mpq_t b)29 ref_mpq_cmp (mpq_t a, mpq_t b)
30 {
31   mpz_t ai, bi;
32   int cc;
33 
34   mpz_init (ai);
35   mpz_init (bi);
36 
37   mpz_mul (ai, NUM (a), DEN (b));
38   mpz_mul (bi, NUM (b), DEN (a));
39   cc = mpz_cmp (ai, bi);
40   mpz_clear (ai);
41   mpz_clear (bi);
42   return cc;
43 }
44 
45 #ifndef SIZE
46 #define SIZE 8	/* increasing this lowers the probability of finding an error */
47 #endif
48 
49 int
main(int argc,char ** argv)50 main (int argc, char **argv)
51 {
52   mpq_t a, b;
53   mp_size_t size;
54   int reps = 10000;
55   int i;
56   int cc, ccref;
57 
58   tests_start ();
59 
60   if (argc == 2)
61      reps = atoi (argv[1]);
62 
63   mpq_init (a);
64   mpq_init (b);
65 
66   for (i = 0; i < reps; i++)
67     {
68       size = urandom () % SIZE - SIZE/2;
69       mpz_random2 (NUM (a), size);
70       do
71 	{
72 	  size = urandom () % SIZE - SIZE/2;
73 	  mpz_random2 (DEN (a), size);
74 	}
75       while (mpz_cmp_ui (DEN (a), 0) == 0);
76 
77       size = urandom () % SIZE - SIZE/2;
78       mpz_random2 (NUM (b), size);
79       do
80 	{
81 	  size = urandom () % SIZE - SIZE/2;
82 	  mpz_random2 (DEN (b), size);
83 	}
84       while (mpz_cmp_ui (DEN (b), 0) == 0);
85 
86       mpq_canonicalize (a);
87       mpq_canonicalize (b);
88 
89       ccref = ref_mpq_cmp (a, b);
90       cc = mpq_cmp (a, b);
91 
92       if (SGN (ccref) != SGN (cc))
93 	abort ();
94     }
95 
96   mpq_clear (a);
97   mpq_clear (b);
98 
99   tests_end ();
100   exit (0);
101 }
102