1/* Test mpf_set_q. 2 3Copyright 2004 Free Software Foundation, Inc. 4 5This file is part of the GNU MP Library. 6 7The GNU MP Library is free software; you can redistribute it and/or modify 8it under the terms of the GNU Lesser General Public License as published by 9the Free Software Foundation; either version 3 of the License, or (at your 10option) any later version. 11 12The GNU MP Library is distributed in the hope that it will be useful, but 13WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 14or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 15License for more details. 16 17You should have received a copy of the GNU Lesser General Public License 18along with the GNU MP Library. If not, see http://www.gnu.org/licenses/. */ 19 20#include <stdio.h> 21#include <stdlib.h> 22#include "gmp.h" 23#include "gmp-impl.h" 24#include "tests.h" 25 26 27void 28check_one (mpf_ptr got, mpq_srcptr q) 29{ 30 mpf_t n, d; 31 32 mpf_set_q (got, q); 33 34 PTR(n) = PTR(&q->_mp_num); 35 SIZ(n) = SIZ(&q->_mp_num); 36 EXP(n) = ABSIZ(&q->_mp_num); 37 38 PTR(d) = PTR(&q->_mp_den); 39 SIZ(d) = SIZ(&q->_mp_den); 40 EXP(d) = ABSIZ(&q->_mp_den); 41 42 if (! refmpf_validate_division ("mpf_set_q", got, n, d)) 43 { 44 mp_trace_base = -16; 45 mpq_trace (" q", q); 46 abort (); 47 } 48} 49 50void 51check_rand (void) 52{ 53 unsigned long min_prec = __GMPF_BITS_TO_PREC (1); 54 gmp_randstate_ptr rands = RANDS; 55 unsigned long prec; 56 mpf_t got; 57 mpq_t q; 58 int i; 59 60 mpf_init (got); 61 mpq_init (q); 62 63 for (i = 0; i < 400; i++) 64 { 65 /* result precision */ 66 prec = min_prec + gmp_urandomm_ui (rands, 20L); 67 refmpf_set_prec_limbs (got, prec); 68 69 /* num */ 70 prec = gmp_urandomm_ui (rands, 20L * GMP_NUMB_BITS); 71 mpz_rrandomb (mpq_numref(q), rands, prec); 72 73 /* possibly negative num */ 74 if (gmp_urandomb_ui (rands, 1L)) 75 mpz_neg (mpq_numref(q), mpq_numref(q)); 76 77 /* den, non-zero */ 78 do { 79 prec = gmp_urandomm_ui (rands, 20L * GMP_NUMB_BITS); 80 mpz_rrandomb (mpq_denref(q), rands, prec); 81 } while (mpz_sgn (mpq_denref(q)) <= 0); 82 83 check_one (got, q); 84 } 85 86 mpf_clear (got); 87 mpq_clear (q); 88} 89 90void 91check_various (void) 92{ 93 mpf_t got; 94 mpq_t q; 95 96 mpf_init (got); 97 mpq_init (q); 98 99 /* 1/1 == 1 */ 100 mpf_set_prec (got, 20L); 101 mpq_set_ui (q, 1L, 1L); 102 mpf_set_q (got, q); 103 MPF_CHECK_FORMAT (got); 104 ASSERT_ALWAYS (mpf_cmp_ui (got, 1L) == 0); 105 106 /* 1/(2^n+1), a case where truncating the divisor would be wrong */ 107 mpf_set_prec (got, 500L); 108 mpq_set_ui (q, 1L, 1L); 109 mpz_mul_2exp (mpq_denref(q), mpq_denref(q), 800L); 110 mpz_add_ui (mpq_denref(q), mpq_denref(q), 1L); 111 check_one (got, q); 112 113 mpf_clear (got); 114 mpq_clear (q); 115} 116 117int 118main (void) 119{ 120 tests_start (); 121 122 check_various (); 123 check_rand (); 124 125 tests_end (); 126 exit (0); 127} 128