PageRenderTime 137ms CodeModel.GetById 3ms app.highlight 117ms RepoModel.GetById 2ms app.codeStats 0ms

/src/gmpy_mpfr.c

http://gmpy.googlecode.com/
C | 2919 lines | 2354 code | 492 blank | 73 comment | 356 complexity | dc9c4e536aaf2cff3e22b6ad4dd1a020 MD5 | raw file
   1/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
   2 * gmpy_mpfr.c                                                             *
   3 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
   4 * Python interface to the GMP or MPIR, MPFR, and MPC multiple precision   *
   5 * libraries.                                                              *
   6 *                                                                         *
   7 * Copyright 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,               *
   8 *           2008, 2009 Alex Martelli                                      *
   9 *                                                                         *
  10 * Copyright 2008, 2009, 2010, 2011, 2012, 2013 Case Van Horsen            *
  11 *                                                                         *
  12 * This file is part of GMPY2.                                             *
  13 *                                                                         *
  14 * GMPY2 is free software: you can redistribute it and/or modify it under  *
  15 * the terms of the GNU Lesser General Public License as published by the  *
  16 * Free Software Foundation, either version 3 of the License, or (at your  *
  17 * option) any later version.                                              *
  18 *                                                                         *
  19 * GMPY2 is distributed in the hope that it will be useful, but WITHOUT    *
  20 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or   *
  21 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public    *
  22 * License for more details.                                               *
  23 *                                                                         *
  24 * You should have received a copy of the GNU Lesser General Public        *
  25 * License along with GMPY2; if not, see <http://www.gnu.org/licenses/>    *
  26 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  27
  28PyDoc_STRVAR(doc_g_mpfr_f2q,
  29"f2q(x,[err]) -> mpq\n\n"
  30"Return the 'best' mpq approximating x to within relative error 'err'.\n"
  31"Default is the precision of x. Uses Stern-Brocot tree to find the\n"
  32"'best' approximation. An 'mpz' is returned if the the denominator\n"
  33"is 1. If 'err'<0, error sought is 2.0 ** err.");
  34
  35static PyObject *
  36Pympfr_f2q(PyObject *self, PyObject *args)
  37{
  38    PympfrObject *err = 0;
  39    PyObject *result;
  40
  41    if (!PyArg_ParseTuple(args, "O&|O&", Pympfr_convert_arg, &self,
  42                          Pympfr_convert_arg, &err)) {
  43        TYPE_ERROR("f2q() requires 'mpfr', ['mpfr'] arguments");
  44        return NULL;
  45    }
  46
  47    result = (PyObject*)stern_brocot((PympfrObject*)self, err, 0, 1);
  48    Py_DECREF(self);
  49    Py_XDECREF((PyObject*)err);
  50    return result;
  51}
  52
  53PyDoc_STRVAR(doc_mpfr,
  54"mpfr() -> mpfr(0.0)\n\n"
  55"     If no argument is given, return mpfr(0.0).\n\n"
  56"mpfr(n[, precison=0]) -> mpfr\n\n"
  57"     Return an 'mpfr' object after converting a numeric value. If\n"
  58"     no precision, or a precision of 0, is specified; the precison\n"
  59"     is taken from the current context.\n\n"
  60"mpfr(s[, precision=0[, [base=0]]) -> mpfr\n\n"
  61"     Return 'mpfr' object after converting a string 's' made up of\n"
  62"     digits in the given base, possibly with fraction-part (with\n"
  63"     period as a separator) and/or exponent-part (with exponent\n"
  64"     marker 'e' for base<=10, else '@'). If no precision, or a\n"
  65"     precision of 0, is specified; the precison is taken from the\n"
  66"     current context. The base of the string representation must\n"
  67"     be 0 or in the interval 2 ... 62. If the base is 0, the leading\n"
  68"     digits of the string are used to identify the base: 0b implies\n"
  69"     base=2, 0x implies base=16, otherwise base=10 is assumed.\n");
  70
  71static PyObject *
  72Pygmpy_mpfr(PyObject *self, PyObject *args, PyObject *keywds)
  73{
  74    PympfrObject *result = 0;
  75    PyObject *arg0;
  76    int base = 0;
  77    Py_ssize_t argc;
  78    /* Assumes mpfr_prec_t is the same as a long. */
  79    mpfr_prec_t bits = 0;
  80    static char *kwlist_s[] = {"s", "precision", "base", NULL};
  81    static char *kwlist_n[] = {"n", "precision", NULL};
  82
  83    argc = PyTuple_Size(args);
  84    if ((argc < 0) || (argc > 3)) {
  85        TYPE_ERROR("mpfr() requires 0 to 3 arguments");
  86        return NULL;
  87    }
  88
  89    if (argc == 0) {
  90        if ((result = (PympfrObject*)Pympfr_new(0))) {
  91            mpfr_set_ui(result->f, 0, context->ctx.mpfr_round);
  92        }
  93        return (PyObject*)result;
  94    }
  95    arg0 = PyTuple_GetItem(args, 0);
  96    if (PyStrOrUnicode_Check(arg0)) {
  97        /* Can have both precision and/or base as keyword arguments. */
  98        if (PyArg_ParseTupleAndKeywords(args, keywds, "O|li", kwlist_s,
  99                                        &arg0, &bits, &base)) {
 100            if ((base!=0) && ((base<2)||(base>62))) {
 101                VALUE_ERROR("base for mpfr() must be 0 or in the "
 102                            "interval 2 ... 62");
 103            }
 104            else if (bits < 0) {
 105                VALUE_ERROR("precision for mpfr() must be >= 0");
 106            }
 107            else {
 108                result = Pympfr_From_PyStr(arg0, base, bits);
 109            }
 110        }
 111        SUBNORMALIZE(result);
 112        return (PyObject*)result;
 113    }
 114
 115    /* Optimize the common case */
 116    if (isReal(arg0) && argc == 1 && !keywds) {
 117        result = Pympfr_From_Real(arg0, bits);
 118        SUBNORMALIZE(result);
 119        return (PyObject*)result;
 120    }
 121
 122    /* Can only have precision as keyword argument. */
 123    if (PyArg_ParseTupleAndKeywords(args, keywds, "O|l", kwlist_n, &arg0, &bits)) {
 124        if (bits < 0) {
 125            VALUE_ERROR("precision for mpfr() must be >= 0");
 126        }
 127        else {
 128            result = Pympfr_From_Real(arg0, bits);
 129            if (!result)
 130                TYPE_ERROR("mpfr() requires numeric or string argument");
 131        }
 132    }
 133    return (PyObject*)result;
 134}
 135
 136/* Implement the .precision attribute of an mpfr. */
 137
 138static PyObject *
 139Pympfr_getprec_attrib(PympfrObject *self, void *closure)
 140{
 141    return PyIntOrLong_FromSsize_t((Py_ssize_t)mpfr_get_prec(self->f));
 142}
 143
 144/* Implement the .rc attribute of an mpfr. */
 145
 146static PyObject *
 147Pympfr_getrc_attrib(PympfrObject *self, void *closure)
 148{
 149    return PyIntOrLong_FromLong((long)self->rc);
 150}
 151
 152/* Implement the .imag attribute of an mpfr. */
 153
 154static PyObject *
 155Pympfr_getimag_attrib(PympfrObject *self, void *closure)
 156{
 157    PympfrObject *result;
 158
 159    if ((result = (PympfrObject*)Pympfr_new(0)))
 160        mpfr_set_zero(result->f, 1);
 161    return (PyObject*)result;
 162}
 163
 164/* Implement the .real attribute of an mpfr. */
 165
 166static PyObject *
 167Pympfr_getreal_attrib(PympfrObject *self, void *closure)
 168{
 169    return (PyObject*)Pympfr_From_Pympfr((PyObject*)self, 0);
 170}
 171
 172/* Implement the nb_bool slot. */
 173
 174static int
 175Pympfr_nonzero(PympfrObject *self)
 176{
 177    return !mpfr_zero_p(self->f);
 178}
 179
 180/* Implement the conjugate() method. */
 181
 182PyDoc_STRVAR(doc_mpfr_conjugate,
 183"x.conjugate() -> mpfr\n\n"
 184"Return the conjugate of x (which is just a copy of x since x is\n"
 185"not a complex number).");
 186
 187static PyObject *
 188Pympfr_conjugate(PyObject *self, PyObject *args)
 189{
 190    return (PyObject*)Pympfr_From_Pympfr(self, 0);
 191}
 192
 193/* Implement the nb_positive slot. */
 194
 195/* TODO: can probably just call Pympfr_From_Real. */
 196
 197static PyObject *
 198Pympfr_pos(PympfrObject *self)
 199{
 200    PympfrObject *result;
 201
 202    if (!(result = (PympfrObject*)Pympfr_new(mpfr_get_prec(self->f))))
 203        return NULL;
 204
 205    mpfr_clear_flags();
 206
 207    /* Since result has the same precision as self, no rounding occurs. */
 208    mpfr_set(result->f, self->f, context->ctx.mpfr_round);
 209    result->round_mode = self->round_mode;
 210    result->rc = self->rc;
 211    /* Force the exponents to be valid. */
 212    result->rc = mpfr_check_range(result->f, result->rc, result->round_mode);
 213    /* Now round result to the current precision. */
 214    result->rc = mpfr_prec_round(result->f, context->ctx.mpfr_prec,
 215                                 context->ctx.mpfr_round);
 216
 217    SUBNORMALIZE(result);
 218    MERGE_FLAGS;
 219    CHECK_FLAGS("__pos__");
 220  done:
 221    if (PyErr_Occurred()) {
 222        Py_XDECREF((PyObject*)result);
 223        result = NULL;
 224    }
 225    return (PyObject*)result;
 226}
 227
 228PyDoc_STRVAR(doc_g_mpfr_get_emin_min,
 229"get_emin_min() -> integer\n\n"
 230"Return the minimum possible exponent that can be set for 'mpfr'.");
 231
 232static PyObject *
 233Pympfr_get_emin_min(PyObject *self, PyObject *args)
 234{
 235    return PyIntOrLong_FromSsize_t((Py_ssize_t)mpfr_get_emin_min());
 236}
 237
 238PyDoc_STRVAR(doc_g_mpfr_get_emax_max,
 239"get_emax_max() -> integer\n\n"
 240"Return the maximum possible exponent that can be set for 'mpfr'.");
 241
 242static PyObject *
 243Pympfr_get_emax_max(PyObject *self, PyObject *args)
 244{
 245    return PyIntOrLong_FromSsize_t((Py_ssize_t)mpfr_get_emax_max());
 246}
 247
 248PyDoc_STRVAR(doc_g_mpfr_get_max_precision,
 249"get_max_precision() -> integer\n\n"
 250"Return the maximum bits of precision that can be used for calculations.\n"
 251"Note: to allow extra precision for intermediate calculations, avoid\n"
 252"setting precision close the maximum precision.");
 253
 254static PyObject *
 255Pympfr_get_max_precision(PyObject *self, PyObject *args)
 256{
 257    return PyIntOrLong_FromSsize_t((Py_ssize_t)MPFR_PREC_MAX);
 258}
 259
 260PyDoc_STRVAR(doc_g_mpfr_get_exp,
 261"get_exp(mpfr) -> integer\n\n"
 262"Return the exponent of an mpfr. Returns 0 for NaN or Infinity and\n"
 263"sets the erange flag and will raise an exception if trap_erange\n"
 264"is set.");
 265
 266static PyObject *
 267Pympfr_get_exp(PyObject *self, PyObject *other)
 268{
 269    PyObject *result = 0;
 270    Py_ssize_t exp;
 271
 272    PARSE_ONE_MPFR_OTHER("get_exp() requires 'mpfr' argument");
 273
 274    if (mpfr_regular_p(Pympfr_AS_MPFR(self))) {
 275        exp = (Py_ssize_t)mpfr_get_exp(Pympfr_AS_MPFR(self));
 276        result = PyIntOrLong_FromSsize_t((Py_ssize_t)exp);
 277    }
 278    else if (mpfr_zero_p(Pympfr_AS_MPFR(self))) {
 279        Py_DECREF(self);
 280        result = PyIntOrLong_FromSsize_t(0);
 281    }
 282    else {
 283        context->ctx.erange = 1;
 284        if (context->ctx.trap_erange) {
 285            GMPY_ERANGE("Can not get exponent from NaN or Infinity.");
 286        }
 287        else {
 288            result = PyIntOrLong_FromSsize_t(0);
 289        }
 290    }
 291    Py_DECREF(self);
 292    return result;
 293}
 294
 295PyDoc_STRVAR(doc_g_mpfr_set_exp,
 296"set_exp(mpfr, n) -> mpfr\n\n"
 297"Set the exponent of an mpfr to n. If n is outside the range of\n"
 298"valid exponents, set_exp() will set the erange flag and either\n"
 299"return the original value or raise an exception if trap_erange\n"
 300"is set.");
 301
 302static PyObject *
 303Pympfr_set_exp(PyObject *self, PyObject *args)
 304{
 305    PympfrObject *result = 0;
 306    long exp = 0;
 307
 308    if (!PyArg_ParseTuple(args, "O&l", Pympfr_convert_arg, &self, &exp)) {
 309        TYPE_ERROR("set_exp() requires 'mpfr', 'integer' arguments");
 310        return NULL;
 311    }
 312
 313    if (!(result = Pympfr_From_Pympfr(self, 0)))
 314        return NULL;
 315    Py_DECREF(self);
 316
 317    result->rc = mpfr_set_exp(Pympfr_AS_MPFR(result), exp);
 318
 319    if (result->rc) {
 320        context->ctx.erange = 1;
 321        if (context->ctx.trap_erange) {
 322            GMPY_ERANGE("New exponent is out-of-bounds.");
 323            Py_DECREF(result);
 324            return NULL;
 325        }
 326    }
 327
 328    return (PyObject*)result;
 329}
 330
 331PyDoc_STRVAR(doc_g_mpfr_set_sign,
 332"set_sign(mpfr, bool) -> mpfr\n\n"
 333"If 'bool' is True, then return an 'mpfr' with the sign bit set.");
 334
 335static PyObject *
 336Pympfr_set_sign(PyObject *self, PyObject *args)
 337{
 338    PympfrObject *result = 0;
 339    PyObject *boolean = 0;
 340    int s;
 341
 342    if (!PyArg_ParseTuple(args, "O&O", Pympfr_convert_arg, &self, &boolean)) {
 343        TYPE_ERROR("set_sign() requires 'mpfr', 'boolean' arguments");
 344        return NULL;
 345    }
 346
 347    if (!(result = (PympfrObject*)Pympfr_new(0)))
 348        return NULL;
 349
 350    s = PyObject_IsTrue(boolean);
 351    if (s == -1) {
 352        TYPE_ERROR("set_sign() requires 'mpfr', 'boolean' arguments");
 353        Py_DECREF(self);
 354        Py_DECREF(boolean);
 355        Py_DECREF(result);
 356        return NULL;
 357    }
 358
 359    result->rc = mpfr_setsign(Pympfr_AS_MPFR(result), Pympfr_AS_MPFR(self),
 360                              s, context->ctx.mpfr_round);
 361
 362    Py_DECREF(self);
 363    Py_DECREF(boolean);
 364    return (PyObject*)result;
 365}
 366
 367PyDoc_STRVAR(doc_g_mpfr_copy_sign,
 368"copy_sign(mpfr, mpfr) -> mpfr\n\n"
 369"Return an 'mpfr' composed of the first argument with the sign of the\n"
 370"second argument.");
 371
 372static PyObject *
 373Pympfr_copy_sign(PyObject *self, PyObject *args)
 374{
 375    PympfrObject *result = 0;
 376    PyObject *other = 0;
 377
 378    if (!PyArg_ParseTuple(args, "O&O&", Pympfr_convert_arg, &self,
 379                          Pympfr_convert_arg, &other)) {
 380        TYPE_ERROR("copy_sign() requires 'mpfr', 'mpfr' arguments");
 381        return NULL;
 382    }
 383
 384    if (!(result = (PympfrObject*)Pympfr_new(0)))
 385        return NULL;
 386
 387    result->rc = mpfr_copysign(Pympfr_AS_MPFR(result), Pympfr_AS_MPFR(self),
 388                              Pympfr_AS_MPFR(other), context->ctx.mpfr_round);
 389
 390    Py_DECREF(self);
 391    Py_DECREF(other);
 392    return (PyObject*)result;
 393}
 394
 395static PyObject *
 396Pympfr_div_2exp(PyObject *self, PyObject *args)
 397{
 398    PympfrObject *result = 0;
 399    unsigned long exp = 0;
 400
 401    if (!PyArg_ParseTuple(args, "O&k", Pympfr_convert_arg, &self, &exp)) {
 402        TYPE_ERROR("div_2exp() requires 'mpfr', 'integer' arguments");
 403        return NULL;
 404    }
 405
 406    if (!(result = (PympfrObject*)Pympfr_new(0)))
 407        return NULL;
 408
 409    mpfr_clear_flags();
 410
 411    result->rc = mpfr_div_2ui(Pympfr_AS_MPFR(result), Pympfr_AS_MPFR(self),
 412                              exp, context->ctx.mpfr_round);
 413
 414    MPFR_CLEANUP_SELF("div_2exp()");
 415}
 416
 417static PyObject *
 418Pympfr_mul_2exp(PyObject *self, PyObject *args)
 419{
 420    PympfrObject *result = 0;
 421    unsigned long exp = 0;
 422
 423    if (!PyArg_ParseTuple(args, "O&k", Pympfr_convert_arg, &self, &exp)) {
 424        TYPE_ERROR("mul_2exp() requires 'mpfr', 'integer' arguments");
 425        return NULL;
 426    }
 427
 428    if (!(result = (PympfrObject*)Pympfr_new(0)))
 429        return NULL;
 430
 431    mpfr_clear_flags();
 432
 433    result->rc = mpfr_mul_2ui(Pympfr_AS_MPFR(result), Pympfr_AS_MPFR(self),
 434                              exp, context->ctx.mpfr_round);
 435
 436    MPFR_CLEANUP_SELF("mul_2exp()");
 437}
 438
 439PyDoc_STRVAR(doc_g_mpfr_set_nan,
 440"nan() -> mpfr\n\n"
 441"Return an 'mpfr' initialized to NaN (Not-A-Number).");
 442
 443static PyObject *
 444Pympfr_set_nan(PyObject *self, PyObject *other)
 445{
 446    PympfrObject *result;
 447
 448    if ((result = (PympfrObject*)Pympfr_new(0)))
 449        mpfr_set_nan(result->f);
 450    return (PyObject*)result;
 451}
 452
 453PyDoc_STRVAR(doc_g_mpfr_set_inf,
 454"inf(n) -> mpfr\n\n"
 455"Return an 'mpfr' initialized to Infinity with the same sign as n.\n"
 456"If n is not given, +Infinity is returned.");
 457
 458static PyObject *
 459Pympfr_set_inf(PyObject *self, PyObject *args)
 460{
 461    PympfrObject *result;
 462    long s = 1;
 463
 464    if (PyTuple_Size(args) == 1) {
 465        s = clong_From_Integer(PyTuple_GET_ITEM(args, 0));
 466        if (s == -1 && PyErr_Occurred()) {
 467            TYPE_ERROR("inf() requires 'int' argument");
 468            return NULL;
 469        }
 470    }
 471
 472    if ((result = (PympfrObject*)Pympfr_new(0)))
 473        mpfr_set_inf(result->f, s<0?-1:1);
 474    return (PyObject*)result;
 475}
 476
 477PyDoc_STRVAR(doc_g_mpfr_set_zero,
 478"zero(n) -> mpfr\n\n"
 479"Return an 'mpfr' inialized to 0.0 with the same sign as n.\n"
 480"If n is not given, +0.0 is returned.");
 481
 482static PyObject *
 483Pympfr_set_zero(PyObject *self, PyObject *args)
 484{
 485    PympfrObject *result;
 486    long s = 1;
 487
 488    if (PyTuple_Size(args) == 1) {
 489        s = clong_From_Integer(PyTuple_GET_ITEM(args, 0));
 490        if (s == -1 && PyErr_Occurred()) {
 491            TYPE_ERROR("zero() requires 'int' argument");
 492            return NULL;
 493        }
 494    }
 495
 496    if ((result = (PympfrObject*)Pympfr_new(0)))
 497        mpfr_set_zero(result->f, s<0?-1:1);
 498    return (PyObject*)result;
 499}
 500
 501PyDoc_STRVAR(doc_g_mpfr_is_signed,
 502"is_signed(x) -> boolean\n\n"
 503"Return True if the sign bit of x is set.");
 504
 505static PyObject *
 506Pympfr_is_signed(PyObject *self, PyObject *other)
 507{
 508    int res;
 509    if(self && Pympfr_Check(self)) {
 510        Py_INCREF(self);
 511    }
 512    else if(Pympfr_Check(other)) {
 513        self = other;
 514        Py_INCREF((PyObject*)self);
 515    }
 516    else if (!(self = (PyObject*)Pympfr_From_Real(other, 0))) {
 517        TYPE_ERROR("is_signed() requires 'mpfr' argument");
 518        return NULL;
 519    }
 520    res = mpfr_signbit(Pympfr_AS_MPFR(self));
 521    Py_DECREF(self);
 522    if (res)
 523        Py_RETURN_TRUE;
 524    else
 525        Py_RETURN_FALSE;
 526}
 527
 528#define MPFR_TEST_OTHER(NAME, msg) \
 529static PyObject * \
 530Pympfr_is_##NAME(PyObject *self, PyObject *other)\
 531{\
 532    int res;\
 533    if(self && Pympfr_Check(self)) {\
 534        Py_INCREF(self);\
 535    }\
 536    else if(Pympfr_Check(other)) {\
 537        self = other;\
 538        Py_INCREF((PyObject*)self);\
 539    }\
 540    else if (!(self = (PyObject*)Pympfr_From_Real(other, 0))) {\
 541        PyErr_SetString(PyExc_TypeError, msg);\
 542        return NULL;\
 543    }\
 544    res = mpfr_##NAME##_p(Pympfr_AS_MPFR(self));\
 545    Py_DECREF(self);\
 546    if (res)\
 547        Py_RETURN_TRUE;\
 548    else\
 549        Py_RETURN_FALSE;\
 550}
 551
 552MPFR_TEST_OTHER(nan, "is_nan() requires 'mpfr' argument");
 553
 554MPFR_TEST_OTHER(inf, "is_infinite() requires 'mpfr' argument");
 555
 556PyDoc_STRVAR(doc_g_mpfr_is_number,
 557"is_number(x) -> boolean\n\n"
 558"Return True if x is an actual number (i.e. not NaN or Infinity);\n"
 559"False otherwise.\n"
 560"Note: is_number() is deprecated; please use is_finite().");
 561
 562MPFR_TEST_OTHER(number, "is_finite() requires 'mpfr' argument");
 563
 564MPFR_TEST_OTHER(zero, "is_zero() requires 'mpfr' argument");
 565
 566PyDoc_STRVAR(doc_g_mpfr_is_regular,
 567"is_regular(x) -> boolean\n\n"
 568"Return True if x is not zero, NaN, or Infinity; False otherwise.");
 569
 570MPFR_TEST_OTHER(regular, "is_regular() requires 'mpfr' argument");
 571
 572PyDoc_STRVAR(doc_mpfr_is_integer,
 573"x.is_integer() -> boolean\n\n"
 574"Return True if x is an integer; False otherwise.");
 575
 576PyDoc_STRVAR(doc_g_mpfr_is_integer,
 577"is_integer(x) -> boolean\n\n"
 578"Return True if x is an integer; False otherwise.");
 579
 580MPFR_TEST_OTHER(integer, "is_integer() requires 'mpfr' argument");
 581
 582/* produce string for an mpfr with requested/defaulted parameters */
 583
 584PyDoc_STRVAR(doc_mpfr_digits,
 585"x.digits([base=10[, prec=0]]) -> (mantissa, exponent, bits)\n\n"
 586"Returns up to 'prec' digits in the given base. If 'prec' is 0, as many\n"
 587"digits that are available are returned. No more digits than available\n"
 588"given x's precision are returned. 'base' must be between 2 and 62,\n"
 589"inclusive. The result is a three element tuple containing the mantissa,\n"
 590"the exponent, and the number of bits of precision.");
 591
 592/* TODO: support keyword arguments. */
 593
 594static PyObject *
 595Pympfr_digits(PyObject *self, PyObject *args)
 596{
 597    int base = 10;
 598    int prec = 0;
 599    PyObject *result;
 600
 601    if (self && Pympfr_Check(self)) {
 602        if (!PyArg_ParseTuple(args, "|ii", &base, &prec))
 603            return NULL;
 604        Py_INCREF(self);
 605    }
 606    else {
 607        if(!PyArg_ParseTuple(args, "O&|ii", Pympfr_convert_arg, &self,
 608                            &base, &prec))
 609        return NULL;
 610    }
 611    result = Pympfr_To_PyStr((PympfrObject*)self, base, prec);
 612    Py_DECREF(self);
 613    return result;
 614}
 615
 616PyDoc_STRVAR(doc_mpfr_integer_ratio,
 617"x.as_integer_ratio() -> (num, den)\n\n"
 618"Return the exact rational equivalent of an mpfr. Value is a tuple\n"
 619"for compatibility with Python's float.as_integer_ratio().");
 620
 621static PyObject *
 622Pympfr_integer_ratio(PyObject *self, PyObject *args)
 623{
 624    PympzObject *num = 0, *den = 0;
 625    mpfr_exp_t temp, twocount;
 626    PyObject *result;
 627
 628    if (mpfr_nan_p(Pympfr_AS_MPFR(self))) {
 629        VALUE_ERROR("Cannot pass NaN to mpfr.as_integer_ratio.");
 630        return NULL;
 631    }
 632
 633    if (mpfr_inf_p(Pympfr_AS_MPFR(self))) {
 634        OVERFLOW_ERROR("Cannot pass Infinity to mpfr.as_integer_ratio.");
 635        return NULL;
 636    }
 637
 638    num = (PympzObject*)Pympz_new();
 639    den = (PympzObject*)Pympz_new();
 640    if (!num || !den) {
 641        Py_XDECREF((PyObject*)num);
 642        Py_XDECREF((PyObject*)den);
 643        return NULL;
 644    }
 645
 646    if (mpfr_zero_p(Pympfr_AS_MPFR(self))) {
 647        mpz_set_ui(num->z, 0);
 648        mpz_set_ui(den->z, 1);
 649    }
 650    else {
 651        temp = mpfr_get_z_2exp(num->z, Pympfr_AS_MPFR(self));
 652        twocount = (mpfr_exp_t)mpz_scan1(num->z, 0);
 653        if (twocount) {
 654            temp += twocount;
 655            mpz_div_2exp(num->z, num->z, twocount);
 656        }
 657        mpz_set_ui(den->z, 1);
 658        if (temp > 0)
 659            mpz_mul_2exp(num->z, num->z, temp);
 660        else if (temp < 0)
 661            mpz_mul_2exp(den->z, den->z, -temp);
 662    }
 663    result = Py_BuildValue("(NN)", (PyObject*)num, (PyObject*)den);
 664    if (!result) {
 665        Py_DECREF((PyObject*)num);
 666        Py_DECREF((PyObject*)den);
 667    }
 668    return result;
 669}
 670
 671PyDoc_STRVAR(doc_mpfr_mantissa_exp,
 672"x.as_mantissa_exp() -> (mantissa,exponent)\n\n"
 673"Return the mantissa and exponent of an mpfr.");
 674
 675static PyObject *
 676Pympfr_mantissa_exp(PyObject *self, PyObject *args)
 677{
 678    PympzObject *mantissa = 0, *exponent = 0;
 679    mpfr_exp_t temp;
 680    PyObject *result;
 681
 682    if (mpfr_nan_p(Pympfr_AS_MPFR(self))) {
 683        VALUE_ERROR("Cannot pass NaN to mpfr.as_mantissa_exp.");
 684        return NULL;
 685    }
 686
 687    if (mpfr_inf_p(Pympfr_AS_MPFR(self))) {
 688        OVERFLOW_ERROR("Cannot pass Infinity to mpfr.as_mantissa_exp.");
 689        return NULL;
 690    }
 691
 692    mantissa = (PympzObject*)Pympz_new();
 693    exponent = (PympzObject*)Pympz_new();
 694    if (!mantissa || !exponent) {
 695        Py_XDECREF((PyObject*)mantissa);
 696        Py_XDECREF((PyObject*)exponent);
 697        return NULL;
 698    }
 699
 700    if (mpfr_zero_p(Pympfr_AS_MPFR(self))) {
 701        mpz_set_ui(mantissa->z, 0);
 702        mpz_set_ui(exponent->z, 1);
 703    }
 704    else {
 705        temp = mpfr_get_z_2exp(mantissa->z, Pympfr_AS_MPFR(self));
 706        mpz_set_si(exponent->z, temp);
 707    }
 708    result = Py_BuildValue("(NN)", (PyObject*)mantissa, (PyObject*)exponent);
 709    if (!result) {
 710        Py_DECREF((PyObject*)mantissa);
 711        Py_DECREF((PyObject*)exponent);
 712    }
 713    return result;
 714}
 715
 716PyDoc_STRVAR(doc_mpfr_simple_fraction,
 717"x.as_simple_fraction([precision=0]) -> mpq\n\n"
 718"Return a simple rational approximation to x. The result will be\n"
 719"accurate to 'precision' bits. If 'precision' is 0, the precision\n"
 720"of 'x' will be used.");
 721
 722static PyObject *
 723Pympfr_simple_fraction(PyObject *self, PyObject *args, PyObject *keywds)
 724{
 725    mpfr_prec_t prec = 0;
 726    static char *kwlist[] = {"precision", NULL};
 727
 728    if (!PyArg_ParseTupleAndKeywords(args, keywds, "|l", kwlist, &prec))
 729        return NULL;
 730
 731    return (PyObject*)stern_brocot((PympfrObject*)self, 0, prec, 0);
 732}
 733
 734static Py_hash_t
 735_mpfr_hash(mpfr_t f)
 736{
 737#ifdef _PyHASH_MODULUS
 738    Py_uhash_t hash = 0;
 739    Py_ssize_t exp;
 740    size_t msize;
 741    int sign;
 742
 743    /* Handle special cases first */
 744    if (!mpfr_number_p(f)) {
 745        if (mpfr_inf_p(f))
 746            if (mpfr_sgn(f) > 0)
 747                return _PyHASH_INF;
 748            else
 749                return -_PyHASH_INF;
 750        else
 751            return _PyHASH_NAN;
 752    }
 753
 754    /* Calculate the number of limbs in the mantissa. */
 755    msize = (f->_mpfr_prec + mp_bits_per_limb - 1) / mp_bits_per_limb;
 756
 757    /* Calculate the hash of the mantissa. */
 758    if (mpfr_sgn(f) > 0) {
 759        hash = mpn_mod_1(f->_mpfr_d, msize, _PyHASH_MODULUS);
 760        sign = 1;
 761    }
 762    else if (mpfr_sgn(f) < 0) {
 763        hash = mpn_mod_1(f->_mpfr_d, msize, _PyHASH_MODULUS);
 764        sign = -1;
 765    }
 766    else {
 767        return 0;
 768    }
 769
 770    /* Calculate the final hash. */
 771    exp = f->_mpfr_exp - (msize * mp_bits_per_limb);
 772    exp = exp >= 0 ? exp % _PyHASH_BITS : _PyHASH_BITS-1-((-1-exp) % _PyHASH_BITS);
 773    hash = ((hash << exp) & _PyHASH_MODULUS) | hash >> (_PyHASH_BITS - exp);
 774
 775    hash *= sign;
 776    if (hash == (Py_uhash_t)-1)
 777        hash = (Py_uhash_t)-2;
 778    return (Py_hash_t)hash;
 779#else
 780    double temp;
 781    temp = mpfr_get_d(f, context->ctx.mpfr_round);
 782    return _Py_HashDouble(temp);
 783#endif
 784}
 785
 786static Py_hash_t
 787Pympfr_hash(PympfrObject *self)
 788{
 789    if (self->hash_cache == -1)
 790        self->hash_cache = _mpfr_hash(self->f);
 791    return self->hash_cache;
 792}
 793
 794/* This function is used in gmpy_mpany. */
 795
 796static PyObject *
 797Pympfr_pow(PyObject *base, PyObject *exp, PyObject *m)
 798{
 799    PympfrObject *tempb, *tempe, *result;
 800#ifdef WITHMPC
 801    PympcObject *mpc_result;
 802#endif
 803
 804    if (m != Py_None) {
 805        TYPE_ERROR("pow() 3rd argument not allowed unless all arguments are integers");
 806        return NULL;
 807    }
 808
 809    tempb = Pympfr_From_Real(base, 0);
 810    tempe = Pympfr_From_Real(exp, 0);
 811
 812    if (!tempe || !tempb) {
 813        Py_XDECREF((PyObject*)tempe);
 814        Py_XDECREF((PyObject*)tempb);
 815        Py_RETURN_NOTIMPLEMENTED;
 816    }
 817
 818    result = (PympfrObject*)Pympfr_new(0);
 819
 820    if (!result) {
 821        Py_DECREF((PyObject*)tempe);
 822        Py_DECREF((PyObject*)tempb);
 823        return NULL;
 824    }
 825
 826    if (mpfr_zero_p(tempb->f) && (mpfr_sgn(tempe->f) < 0)) {
 827        context->ctx.divzero = 1;
 828        if (context->ctx.trap_divzero) {
 829            GMPY_DIVZERO("zero cannot be raised to a negative power");
 830            goto done;
 831        }
 832    }
 833
 834    mpfr_clear_flags();
 835    result->rc = mpfr_pow(result->f, tempb->f,
 836                          tempe->f, context->ctx.mpfr_round);
 837#ifdef WITHMPC
 838    if (result && mpfr_nanflag_p() && context->ctx.allow_complex) {
 839        /* If we don't get a valid result, or the result is a nan, then just
 840         * return the original mpfr value. */
 841        if (!(mpc_result = (PympcObject*)Pympc_pow(base, exp, m)) ||
 842            MPC_IS_NAN_P(mpc_result)) {
 843
 844            Py_XDECREF((PyObject*)mpc_result);
 845            context->ctx.invalid = 1;
 846            GMPY_INVALID("invalid operation in 'mpfr' pow()");
 847            goto done;
 848        }
 849        /* return a valid complex result */
 850        Py_DECREF(result);
 851        result = (PympfrObject*)mpc_result;
 852        goto done;
 853    }
 854#endif
 855
 856    SUBNORMALIZE(result)
 857    MERGE_FLAGS
 858    CHECK_FLAGS("pow()")
 859  done:
 860    Py_DECREF((PyObject*)tempe);
 861    Py_DECREF((PyObject*)tempb);
 862    if (PyErr_Occurred()) {
 863        Py_XDECREF((PyObject*)result);
 864        result = NULL;
 865    }
 866    return (PyObject*)result;
 867}
 868
 869#define MPFR_CONST(NAME) \
 870static PyObject * \
 871Pympfr_##NAME(PyObject *self, PyObject *args, PyObject *keywds) \
 872{ \
 873    PympfrObject *result; \
 874    mpfr_prec_t bits = 0; \
 875    static char *kwlist[] = {"precision", NULL}; \
 876    if (!PyArg_ParseTupleAndKeywords(args, keywds, "|l", kwlist, &bits)) return NULL; \
 877    if ((result = (PympfrObject*)Pympfr_new(bits))) { \
 878        mpfr_clear_flags(); \
 879        result->rc = mpfr_##NAME(result->f, context->ctx.mpfr_round); \
 880        MERGE_FLAGS \
 881        CHECK_FLAGS(#NAME "()") \
 882    } \
 883  done: \
 884    return (PyObject*)result; \
 885}
 886
 887PyDoc_STRVAR(doc_mpfr_const_pi,
 888"const_pi([precision=0]) -> mpfr\n\n"
 889"Return the constant pi using the specified precision. If no\n"
 890"precision is specified, the default precision is used.");
 891
 892MPFR_CONST(const_pi)
 893
 894PyDoc_STRVAR(doc_mpfr_const_euler,
 895"const_euler([precision=0]) -> mpfr\n\n"
 896"Return the euler constant using the specified precision. If no\n"
 897"precision is specified, the default precision is used.");
 898
 899MPFR_CONST(const_euler)
 900
 901PyDoc_STRVAR(doc_mpfr_const_log2,
 902"const_log2([precision=0]) -> mpfr\n\n"
 903"Return the log2 constant  using the specified precision. If no\n"
 904"precision is specified, the default precision is used.");
 905
 906MPFR_CONST(const_log2)
 907
 908PyDoc_STRVAR(doc_mpfr_const_catalan,
 909"const_catalan([precision=0]) -> mpfr\n\n"
 910"Return the catalan constant  using the specified precision. If no\n"
 911"precision is specified, the default precision is used.");
 912
 913MPFR_CONST(const_catalan)
 914
 915static PyObject *
 916Pympfr_sqrt(PyObject *self, PyObject *other)
 917{
 918    PympfrObject *result;
 919
 920    PARSE_ONE_MPFR_OTHER("sqrt() requires 'mpfr' argument");
 921
 922#ifdef WITHMPC
 923    if (mpfr_sgn(Pympfr_AS_MPFR(self)) < 0 && context->ctx.allow_complex) {
 924        Py_DECREF(self);
 925        return Pympc_sqrt(self, other);
 926    }
 927#endif
 928
 929    if (!(result = (PympfrObject*)Pympfr_new(0))) {
 930        Py_DECREF(self);
 931        return NULL;
 932    }
 933
 934    mpfr_clear_flags();
 935    result->rc = mpfr_sqrt(result->f, Pympfr_AS_MPFR(self),
 936                           context->ctx.mpfr_round);
 937
 938    MPFR_CLEANUP_SELF("sqrt()");
 939}
 940
 941PyDoc_STRVAR(doc_g_mpfr_rec_sqrt,
 942"rec_sqrt(x) -> mpfr\n\n"
 943"Return the reciprocal of the square root of x.");
 944
 945static PyObject *
 946Pympfr_rec_sqrt(PyObject *self, PyObject *other)
 947{
 948    PympfrObject *result;
 949
 950    PARSE_ONE_MPFR_OTHER("rec_sqrt() requires 'mpfr' argument");
 951
 952    if (!(result = (PympfrObject*)Pympfr_new(0)))
 953        goto done;
 954
 955    mpfr_clear_flags();
 956    result->rc = mpfr_rec_sqrt(result->f, Pympfr_AS_MPFR(self),
 957                               context->ctx.mpfr_round);
 958
 959    MPFR_CLEANUP_SELF("rec_sqrt()");
 960}
 961
 962PyDoc_STRVAR(doc_mpfr_root,
 963"root(x, n) -> mpfr\n\n"
 964"Return n-th root of x. The result always an 'mpfr'.");
 965
 966static PyObject *
 967Pympfr_root(PyObject *self, PyObject *args)
 968{
 969    long n;
 970    PympfrObject *result;
 971
 972    PARSE_ONE_MPFR_REQ_CLONG(&n, "root() requires 'mpfr','int' arguments");
 973
 974    if (!(result = (PympfrObject*)Pympfr_new(0)))
 975        goto done;
 976
 977    if (n <= 0) {
 978        VALUE_ERROR("n must be > 0");
 979        goto done;
 980    }
 981
 982    mpfr_clear_flags();
 983    result->rc = mpfr_root(result->f, Pympfr_AS_MPFR(self), n,
 984                           context->ctx.mpfr_round);
 985
 986    MPFR_CLEANUP_SELF("root()");
 987}
 988
 989PyDoc_STRVAR(doc_g_mpfr_round2,
 990"round2(x[, n]) -> mpfr\n\n"
 991"Return x rounded to n bits. Uses default precision if n is not\n"
 992"specified. See round_away() to access the mpfr_round() function.");
 993
 994static PyObject *
 995Pympfr_round2(PyObject *self, PyObject *args)
 996{
 997    mpfr_prec_t prec = context->ctx.mpfr_prec;
 998    PympfrObject *result = 0;
 999
1000    PARSE_ONE_MPFR_OPT_CLONG(&prec,
1001            "round2() requires 'mpfr',['int'] arguments");
1002
1003    if (prec < MPFR_PREC_MIN || prec > MPFR_PREC_MAX) {
1004        VALUE_ERROR("invalid precision");
1005        goto done;
1006    }
1007
1008    if (!(result = (PympfrObject*)Pympfr_new(mpfr_get_prec(Pympfr_AS_MPFR(self))))) {
1009        goto done;
1010    }
1011
1012    mpfr_clear_flags();
1013    /* Duplicate the code from Pympfr_pos. */
1014    mpfr_set(result->f, Pympfr_AS_MPFR(self), context->ctx.mpfr_round);
1015    result->round_mode = ((PympfrObject*)self)->round_mode;
1016    result->rc = ((PympfrObject*)self)->rc;
1017    result->rc = mpfr_check_range(result->f, result->rc, result->round_mode);
1018    result->rc = mpfr_prec_round(result->f, prec, context->ctx.mpfr_round);
1019
1020    MPFR_CLEANUP_SELF("round2()");
1021}
1022
1023PyDoc_STRVAR(doc_g_mpfr_round10,
1024"__round__(x[, n = 0]) -> mpfr\n\n"
1025"Return x rounded to n decimal digits before (n < 0) or after (n > 0)\n"
1026"the decimal point. Rounds to an integer if n is not specified.");
1027
1028static PyObject *
1029Pympfr_round10(PyObject *self, PyObject *args)
1030{
1031    Py_ssize_t digits = 0;
1032    mpz_t temp;
1033    PympfrObject *resultf = 0;
1034    PympzObject *resultz;
1035
1036    /* If the size of args is 0, we just return an mpz. */
1037
1038    if (PyTuple_GET_SIZE(args) == 0) {
1039        if ((resultz = (PympzObject*)Pympz_new())) {
1040            if (mpfr_nan_p(Pympfr_AS_MPFR(self))) {
1041                Py_DECREF((PyObject*)resultz);
1042                VALUE_ERROR("'mpz' does not support NaN");
1043                return NULL;
1044            }
1045            if (mpfr_inf_p(Pympfr_AS_MPFR(self))) {
1046                Py_DECREF((PyObject*)resultz);
1047                OVERFLOW_ERROR("'mpz' does not support Infinity");
1048                return NULL;
1049            }
1050            /* return code is ignored */
1051            mpfr_get_z(resultz->z, Pympfr_AS_MPFR(self), MPFR_RNDN);
1052        }
1053        return (PyObject*)resultz;
1054    }
1055
1056    /* Now we need to return an mpfr, so handle the simple cases. */
1057
1058    if (!mpfr_regular_p(Pympfr_AS_MPFR(self))) {
1059        Py_INCREF(self);
1060        return self;
1061    }
1062
1063    if (PyTuple_GET_SIZE(args) > 1) {
1064        TYPE_ERROR("Too many arguments for __round__().");
1065        return NULL;
1066    }
1067
1068    if (PyTuple_GET_SIZE(args) == 1) {
1069        digits = ssize_t_From_Integer(PyTuple_GET_ITEM(args, 0));
1070        if (digits == -1 && PyErr_Occurred()) {
1071            TYPE_ERROR("__round__() requires 'int' argument");
1072            return NULL;
1073        }
1074    }
1075
1076    /* TODO: better error analysis, or else convert the mpfr to an exact
1077     * fraction, round the fraction, and then convert back to an mpfr.
1078     */
1079
1080    resultf = (PympfrObject*)Pympfr_new(mpfr_get_prec(Pympfr_AS_MPFR(self))+100);
1081    if (!resultf)
1082        return NULL;
1083
1084    mpz_inoc(temp);
1085    mpz_ui_pow_ui(temp, 10, digits > 0 ? digits : -digits);
1086    if (digits >= 0) {
1087        mpfr_mul_z(resultf->f, Pympfr_AS_MPFR(self), temp, MPFR_RNDN);
1088    }
1089    else {
1090        mpfr_div_z(resultf->f, Pympfr_AS_MPFR(self), temp, MPFR_RNDN);
1091    }
1092
1093    mpfr_rint(resultf->f, resultf->f, MPFR_RNDN);
1094
1095    if (digits >= 0) {
1096        mpfr_div_z(resultf->f, resultf->f, temp, MPFR_RNDN);
1097    }
1098    else {
1099        mpfr_mul_z(resultf->f, resultf->f, temp, MPFR_RNDN);
1100    }
1101    mpfr_prec_round(resultf->f, mpfr_get_prec(Pympfr_AS_MPFR(self)), MPFR_RNDN);
1102
1103    mpz_cloc(temp);
1104    return((PyObject*)resultf);
1105}
1106
1107PyDoc_STRVAR(doc_g_mpfr_reldiff,
1108"reldiff(x, y) -> mpfr\n\n"
1109"Return the relative difference between x and y. Result is equal to\n"
1110"abs(x-y)/x.");
1111
1112static PyObject *
1113Pympfr_reldiff(PyObject *self, PyObject *args)
1114{
1115    PympfrObject *result;
1116    PyObject *other;
1117
1118    PARSE_TWO_MPFR_ARGS(other, "reldiff() requires 'mpfr','mpfr' arguments");
1119
1120    if (!(result = (PympfrObject*)Pympfr_new(0))) {
1121        Py_DECREF(self);
1122        Py_DECREF(other);
1123        return NULL;
1124    }
1125
1126    /* mpfr_reldiff doesn't guarantee correct rounding and doesn't appear
1127     * to set any exceptions.
1128     */
1129    mpfr_reldiff(result->f, Pympfr_AS_MPFR(self), Pympfr_AS_MPFR(other),
1130                 context->ctx.mpfr_round);
1131    result->rc = 0;
1132    Py_DECREF(self);
1133    Py_DECREF(other);
1134    return (PyObject*)result;
1135}
1136
1137static PyObject *
1138Pympfr_sign(PyObject *self, PyObject *other)
1139{
1140    long sign;
1141
1142    PARSE_ONE_MPFR_OTHER("sign() requires 'mpfr' argument");
1143
1144    mpfr_clear_flags();
1145    sign = mpfr_sgn(Pympfr_AS_MPFR(self));
1146
1147    MERGE_FLAGS;
1148    CHECK_ERANGE("range error in 'mpfr' sign(), NaN argument");
1149
1150  done:
1151    Py_DECREF((PyObject*)self);
1152    if (PyErr_Occurred())
1153        return NULL;
1154    else
1155        return PyIntOrLong_FromLong(sign);
1156}
1157
1158#define MPFR_MONOP(NAME) \
1159static PyObject * \
1160Py##NAME(PympfrObject *x) \
1161{ \
1162    PympfrObject *r; \
1163    if (!(r = (PympfrObject*)Pympfr_new(0))) \
1164        return NULL; \
1165    if (Pympfr_CheckAndExp(x)) { \
1166        r->rc = NAME(r->f, x->f, context->ctx.mpfr_round); \
1167    } \
1168    else { \
1169        mpfr_set(r->f, x->f, context->ctx.mpfr_round); \
1170        r->round_mode = x->round_mode; \
1171        r->rc = x->rc; \
1172        mpfr_clear_flags(); \
1173        mpfr_check_range(r->f, r->rc, r->round_mode); \
1174        r->rc = NAME(r->f, r->f, context->ctx.mpfr_round); \
1175        MERGE_FLAGS; \
1176        CHECK_FLAGS(#NAME "()"); \
1177    } \
1178  done: \
1179    return (PyObject *) r; \
1180}
1181
1182MPFR_MONOP(mpfr_abs)
1183MPFR_MONOP(mpfr_neg)
1184
1185#define MPFR_UNIOP_NOROUND(NAME) \
1186static PyObject * \
1187Pympfr_##NAME(PyObject* self, PyObject *other) \
1188{ \
1189    PympfrObject *result; \
1190    PARSE_ONE_MPFR_OTHER(#NAME "() requires 'mpfr' argument"); \
1191    if (!(result = (PympfrObject*)Pympfr_new(0))) goto done; \
1192    mpfr_clear_flags(); \
1193    result->rc = mpfr_##NAME(result->f, Pympfr_AS_MPFR(self)); \
1194    MPFR_CLEANUP_SELF(#NAME "()"); \
1195}
1196
1197PyDoc_STRVAR(doc_mpfr_ceil,
1198"x.__ceil__() -> mpfr\n\n"
1199"Return an 'mpfr' that is the smallest integer >= x.");
1200
1201PyDoc_STRVAR(doc_g_mpfr_ceil,
1202"ceil(x) ->mpfr\n\n"
1203"Return an 'mpfr' that is the smallest integer >= x.");
1204
1205MPFR_UNIOP_NOROUND(ceil)
1206
1207PyDoc_STRVAR(doc_mpfr_floor,
1208"x.__floor__() -> mpfr\n\n"
1209"Return an 'mpfr' that is the smallest integer <= x.");
1210
1211PyDoc_STRVAR(doc_g_mpfr_floor,
1212"floor(x) -> mpfr\n\n"
1213"Return an 'mpfr' that is the smallest integer <= x.");
1214
1215MPFR_UNIOP_NOROUND(floor);
1216
1217PyDoc_STRVAR(doc_mpfr_trunc,
1218"x.__trunc__() -> mpfr\n\n"
1219"Return an 'mpfr' that is truncated towards 0. Same as\n"
1220"x.floor() if x>=0 or x.ceil() if x<0.");
1221
1222PyDoc_STRVAR(doc_g_mpfr_trunc,
1223"trunc(x) -> mpfr\n\n"
1224"Return an 'mpfr' that is x truncated towards 0. Same as\n"
1225"x.floor() if x>=0 or x.ceil() if x<0.");
1226
1227MPFR_UNIOP_NOROUND(trunc)
1228
1229PyDoc_STRVAR(doc_g_mpfr_round_away,
1230"round_away(x) -> mpfr\n\n"
1231"Return an 'mpfr' that is x rounded to the nearest integer,\n"
1232"with ties rounded away from 0.");
1233
1234static PyObject *
1235Pympfr_round_away(PyObject* self, PyObject *other)
1236{
1237    PympfrObject *result;
1238
1239    PARSE_ONE_MPFR_OTHER("round_away() requires 'mpfr' argument");
1240    if (!(result = (PympfrObject*)Pympfr_new(0)))
1241        goto done;
1242    mpfr_clear_flags();
1243    result->rc = mpfr_round(result->f, Pympfr_AS_MPFR(self));
1244    MPFR_CLEANUP_SELF("round_away()");
1245}
1246
1247#define MPFR_UNIOP(NAME) \
1248static PyObject * \
1249Pympfr_##NAME(PyObject* self, PyObject *other) \
1250{ \
1251    PympfrObject *result; \
1252    PARSE_ONE_MPFR_OTHER(#NAME "() requires 'mpfr' argument"); \
1253    if (!(result = (PympfrObject*)Pympfr_new(0))) goto done; \
1254    mpfr_clear_flags(); \
1255    result->rc = mpfr_##NAME(result->f, Pympfr_AS_MPFR(self), context->ctx.mpfr_round); \
1256    MPFR_CLEANUP_SELF(#NAME "()"); \
1257}
1258
1259PyDoc_STRVAR(doc_g_mpfr_rint,
1260"rint(x) -> mpfr\n\n"
1261"Return x rounded to the nearest integer using the current rounding\n"
1262"mode.");
1263
1264MPFR_UNIOP(rint)
1265
1266PyDoc_STRVAR(doc_g_mpfr_rint_ceil,
1267"rint_ceil(x) -> mpfr\n\n"
1268"Return x rounded to the nearest integer by first rounding to the\n"
1269"next higher or equal integer and then, if needed, using the current\n"
1270"rounding mode.");
1271
1272MPFR_UNIOP(rint_ceil)
1273
1274PyDoc_STRVAR(doc_g_mpfr_rint_floor,
1275"rint_floor(x) -> mpfr\n\n"
1276"Return x rounded to the nearest integer by first rounding to the\n"
1277"next lower or equal integer and then, if needed, using the current\n"
1278"rounding mode.");
1279
1280MPFR_UNIOP(rint_floor)
1281
1282PyDoc_STRVAR(doc_g_mpfr_rint_round,
1283"rint_round(x) -> mpfr\n\n"
1284"Return x rounded to the nearest integer by first rounding to the\n"
1285"nearest integer (ties away from 0) and then, if needed, using\n"
1286"the current rounding mode.");
1287
1288MPFR_UNIOP(rint_round)
1289
1290PyDoc_STRVAR(doc_g_mpfr_rint_trunc,
1291"rint_trunc(x) -> mpfr\n\n"
1292"Return x rounded to the nearest integer by first rounding towards\n"
1293"zero and then, if needed, using the current rounding mode.");
1294
1295MPFR_UNIOP(rint_trunc)
1296
1297PyDoc_STRVAR(doc_g_mpfr_frac,
1298"frac(x) -> mpfr\n\n"
1299"Return fractional part of x.");
1300
1301MPFR_UNIOP(frac)
1302
1303PyDoc_STRVAR(doc_g_mpfr_modf,
1304"modf(x) -> (mpfr, mpfr)\n\n"
1305"Return a tuple containing the integer and fractional portions\n"
1306"of x.");
1307
1308static PyObject *
1309Pympfr_modf(PyObject *self, PyObject *other)
1310{
1311    PympfrObject *s, *c;
1312    PyObject *result;
1313    int code;
1314
1315    PARSE_ONE_MPFR_OTHER("modf() requires 'mpfr' argument");
1316
1317    s = (PympfrObject*)Pympfr_new(0);
1318    c = (PympfrObject*)Pympfr_new(0);
1319    result = PyTuple_New(2);
1320    if (!s || !c || !result)
1321        goto done;
1322
1323    mpfr_clear_flags();
1324    code = mpfr_modf(s->f, c->f, Pympfr_AS_MPFR(self),
1325                     context->ctx.mpfr_round);
1326    s->rc = code & 0x03;
1327    c->rc = code >> 2;
1328    if (s->rc == 2) s->rc = -1;
1329    if (c->rc == 2) c->rc = -1;
1330    SUBNORMALIZE(s);
1331    SUBNORMALIZE(c);
1332    MERGE_FLAGS;
1333    CHECK_FLAGS("modf()");
1334
1335  done:
1336    Py_DECREF(self);
1337    if (PyErr_Occurred()) {
1338        Py_XDECREF((PyObject*)s);
1339        Py_XDECREF((PyObject*)c);
1340        Py_XDECREF(result);
1341        result = NULL;
1342    }
1343    else {
1344        PyTuple_SET_ITEM(result, 0, (PyObject*)s);
1345        PyTuple_SET_ITEM(result, 1, (PyObject*)c);
1346    }
1347    return result;
1348}
1349
1350/* Needed for square() in mpz_mpany.c */
1351
1352MPFR_UNIOP(sqr)
1353
1354PyDoc_STRVAR(doc_g_mpfr_cbrt,
1355"cbrt(x) -> mpfr\n\n"
1356"Return the cube root of x.");
1357
1358MPFR_UNIOP(cbrt)
1359
1360/* Called via gmpy_mpany so doc-string is there. */
1361
1362MPFR_UNIOP(log)
1363
1364PyDoc_STRVAR(doc_g_mpfr_log2,
1365"log2(x) -> mpfr\n\n"
1366"Return base-2 logarithm of x.");
1367
1368MPFR_UNIOP(log2)
1369
1370/* Called via gmpy_mpany so doc-string is there. */
1371
1372MPFR_UNIOP(log10)
1373
1374/* Called via gmpy_mpany so doc-string is there. */
1375
1376MPFR_UNIOP(exp)
1377
1378PyDoc_STRVAR(doc_g_mpfr_exp2,
1379"exp2(x) -> mpfr\n\n"
1380"Return 2**x.");
1381
1382MPFR_UNIOP(exp2)
1383
1384PyDoc_STRVAR(doc_g_mpfr_exp10,
1385"exp10(x) -> mpfr\n\n"
1386"Return 10**x.");
1387
1388MPFR_UNIOP(exp10)
1389
1390MPFR_UNIOP(sin)
1391
1392MPFR_UNIOP(cos)
1393
1394MPFR_UNIOP(tan)
1395
1396PyDoc_STRVAR(doc_g_mpfr_sec,
1397"sec(x) -> mpfr\n\n"
1398"Return secant of x; x in radians.");
1399
1400MPFR_UNIOP(sec)
1401
1402PyDoc_STRVAR(doc_g_mpfr_csc,
1403"csc(x) -> mpfr\n\n"
1404"Return cosecant of x; x in radians.");
1405
1406MPFR_UNIOP(csc)
1407
1408PyDoc_STRVAR(doc_g_mpfr_cot,
1409"cot(x) -> mpfr\n\n"
1410"Return cotangent of x; x in radians.");
1411
1412MPFR_UNIOP(cot)
1413
1414static PyObject *
1415Pympfr_acos(PyObject* self, PyObject *other)
1416{
1417    PympfrObject *result;
1418
1419    PARSE_ONE_MPFR_OTHER("acos() requires 'mpfr' argument");
1420
1421#ifdef WITHMPC
1422    if (!mpfr_nan_p(Pympfr_AS_MPFR(self)) &&
1423            (mpfr_cmp_si(Pympfr_AS_MPFR(self), 1) > 0 ||
1424            mpfr_cmp_si(Pympfr_AS_MPFR(self), -1) < 0) &&
1425            context->ctx.allow_complex) {
1426        Py_DECREF(self);
1427        return Pympc_acos(self, other);
1428    }
1429#endif
1430
1431    if (!(result = (PympfrObject*)Pympfr_new(0))) {
1432        Py_DECREF(self);
1433        return NULL;
1434    }
1435    mpfr_clear_flags();
1436    result->rc = mpfr_acos(result->f, Pympfr_AS_MPFR(self),
1437                           context->ctx.mpfr_round);
1438    MPFR_CLEANUP_SELF("acos()");
1439}
1440
1441static PyObject *
1442Pympfr_asin(PyObject* self, PyObject *other)
1443{
1444    PympfrObject *result;
1445
1446    PARSE_ONE_MPFR_OTHER("asin() requires 'mpfr' argument");
1447
1448#ifdef WITHMPC
1449    if (!mpfr_nan_p(Pympfr_AS_MPFR(self)) &&
1450            (mpfr_cmp_si(Pympfr_AS_MPFR(self), 1) > 0 ||
1451            mpfr_cmp_si(Pympfr_AS_MPFR(self), -1) < 0) &&
1452            context->ctx.allow_complex) {
1453        Py_DECREF(self);
1454        return Pympc_asin(self, other);
1455    }
1456#endif
1457
1458    if (!(result = (PympfrObject*)Pympfr_new(0))) {
1459        Py_DECREF(self);
1460        return NULL;
1461    }
1462    mpfr_clear_flags();
1463    result->rc = mpfr_asin(result->f, Pympfr_AS_MPFR(self),
1464                           context->ctx.mpfr_round);
1465    MPFR_CLEANUP_SELF("asin()");
1466}
1467
1468MPFR_UNIOP(atan)
1469
1470MPFR_UNIOP(cosh)
1471
1472MPFR_UNIOP(sinh)
1473
1474MPFR_UNIOP(tanh)
1475
1476PyDoc_STRVAR(doc_g_mpfr_sech,
1477"sech(x) -> mpfr\n\n"
1478"Returns hyperbolic secant of x.");
1479
1480MPFR_UNIOP(sech)
1481
1482PyDoc_STRVAR(doc_g_mpfr_csch,
1483"csch(x) -> mpfr\n\n"
1484"Return hyperbolic cosecant of x.");
1485
1486MPFR_UNIOP(csch)
1487
1488PyDoc_STRVAR(doc_g_mpfr_coth,
1489"coth(x) -> mpfr\n\n"
1490"Return hyperbolic cotangent of x.");
1491
1492MPFR_UNIOP(coth)
1493
1494MPFR_UNIOP(acosh)
1495
1496MPFR_UNIOP(asinh)
1497
1498static PyObject *
1499Pympfr_atanh(PyObject* self, PyObject *other)
1500{
1501    PympfrObject *result;
1502
1503    PARSE_ONE_MPFR_OTHER("atanh() requires 'mpfr' argument");
1504
1505#ifdef WITHMPC
1506    if (!mpfr_nan_p(Pympfr_AS_MPFR(self)) &&
1507            (mpfr_cmp_si(Pympfr_AS_MPFR(self), 1) > 0 ||
1508            mpfr_cmp_si(Pympfr_AS_MPFR(self), -1) < 0) &&
1509            context->ctx.allow_complex) {
1510        Py_DECREF(self);
1511        return Pympc_atanh(self, other);
1512    }
1513#endif
1514
1515    if (!(result = (PympfrObject*)Pympfr_new(0))) {
1516        Py_DECREF(self);
1517        return NULL;
1518    }
1519    mpfr_clear_flags();
1520    result->rc = mpfr_asin(result->f, Pympfr_AS_MPFR(self),
1521                           context->ctx.mpfr_round);
1522    MPFR_CLEANUP_SELF("atanh()");
1523}
1524
1525
1526PyDoc_STRVAR(doc_g_mpfr_log1p,
1527"log1p(x) -> mpfr\n\n"
1528"Return logarithm of (1+x).");
1529
1530MPFR_UNIOP(log1p)
1531
1532PyDoc_STRVAR(doc_g_mpfr_expm1,
1533"expm1(x) -> mpfr\n\n"
1534"Return exponential(x) - 1.");
1535
1536MPFR_UNIOP(expm1)
1537
1538PyDoc_STRVAR(doc_g_mpfr_eint,
1539"eint(x) -> mpfr\n\n"
1540"Return exponential integral of x.");
1541
1542MPFR_UNIOP(eint)
1543
1544PyDoc_STRVAR(doc_g_mpfr_li2,
1545"li2(x) -> mpfr\n\n"
1546"Return real part of dilogarithm of x.");
1547
1548MPFR_UNIOP(li2)
1549
1550PyDoc_STRVAR(doc_g_mpfr_gamma,
1551"gamma(x) -> mpfr\n\n"
1552"Return gamma of x.");
1553
1554MPFR_UNIOP(gamma)
1555
1556PyDoc_STRVAR(doc_g_mpfr_lngamma,
1557"lngamma(x) -> mpfr\n\n"
1558"Return logarithm of gamma(x).");
1559
1560MPFR_UNIOP(lngamma)
1561
1562PyDoc_STRVAR(doc_g_mpfr_lgamma,
1563"lgamma(x) -> (mpfr, int)\n\n"
1564"Return a tuple containing the logarithm of the absolute value of\n"
1565"gamma(x) and the sign of gamma(x)");
1566
1567static PyObject *
1568Pympfr_lgamma(PyObject* self, PyObject *other)
1569{
1570    PyObject *result;
1571    PympfrObject *value;
1572    int signp = 0;
1573
1574    PARSE_ONE_MPFR_OTHER("lgamma() requires 'mpfr' argument");
1575
1576    value = (PympfrObject*)Pympfr_new(0);
1577    result = PyTuple_New(2);
1578    if (!value || !result)
1579        goto done;
1580
1581    mpfr_clear_flags();
1582    value->rc = mpfr_lgamma(value->f, &signp, Pympfr_AS_MPFR(self),
1583                            context->ctx.mpfr_round);
1584    SUBNORMALIZE(value);
1585    MERGE_FLAGS;
1586    CHECK_FLAGS("lgamma()");
1587
1588  done:
1589    Py_DECREF(self);
1590    if (PyErr_Occurred()) {
1591        Py_XDECREF(result);
1592        Py_XDECREF((PyObject*)value);
1593        result = NULL;
1594    }
1595    else {
1596        PyTuple_SET_ITEM(result, 0, (PyObject*)value);
1597        PyTuple_SET_ITEM(result, 1, PyIntOrLong_FromLong((long)signp));
1598    }
1599    return result;
1600}
1601
1602PyDoc_STRVAR(doc_g_mpfr_digamma,
1603"digamma(x) -> mpfr\n\n"
1604"Return digamma of x.");
1605
1606MPFR_UNIOP(digamma)
1607
1608PyDoc_STRVAR(doc_g_mpfr_zeta,
1609"zeta(x) -> mpfr\n\n"
1610"Return Riemann zeta of x.");
1611
1612MPFR_UNIOP(zeta)
1613
1614PyDoc_STRVAR(doc_g_mpfr_erf,
1615"erf(x) -> mpfr\n\n"
1616"Return error function of x.");
1617
1618MPFR_UNIOP(erf)
1619
1620PyDoc_STRVAR(doc_g_mpfr_erfc,
1621"erfc(x) -> mpfr\n\n"
1622"Return complementary error function of x.");
1623
1624MPFR_UNIOP(erfc)
1625
1626PyDoc_STRVAR(doc_g_mpfr_j0,
1627"j0(x) -> mpfr\n\n"
1628"Return first kind Bessel function of order 0 of x.");
1629
1630MPFR_UNIOP(j0)
1631
1632PyDoc_STRVAR(doc_g_mpfr_j1,
1633"j1(x) -> mpfr\n\n"
1634"Return first kind Bessel function of order 1 of x.");
1635
1636MPFR_UNIOP(j1)
1637
1638PyDoc_STRVAR(doc_g_mpfr_jn,
1639"jn(x,n) -> mpfr\n\n"
1640"Return the first kind Bessel function of order n of x.");
1641
1642static PyObject *
1643Pympfr_jn(PyObject *self, PyObject *args)
1644{
1645    PympfrObject *result;
1646    long n = 0;
1647
1648    PARSE_ONE_MPFR_REQ_CLONG(&n, "jn() requires 'mpfr','int' arguments");
1649
1650    if (!(result = (PympfrObject*)Pympfr_new(0)))
1651        goto done;
1652
1653    mpfr_clear_flags();
1654    result->rc = mpfr_jn(result->f, n, Pympfr_AS_MPFR(self),
1655                         context->ctx.mpfr_round);
1656    MPFR_CLEANUP_SELF("jn()");
1657}
1658
1659PyDoc_STRVAR(doc_g_mpfr_y0,
1660"y0(x) -> mpfr\n\n"
1661"Return second kind Bessel function of order 0 of x.");
1662
1663MPFR_UNIOP(y0)
1664
1665PyDoc_STRVAR(doc_g_mpfr_y1,
1666"y1(x) -> mpfr\n\n"
1667"Return second kind Bessel function of order 1 of x.");
1668
1669MPFR_UNIOP(y1)
1670
1671PyDoc_STRVAR(doc_g_mpfr_yn,
1672"yn(x,n) -> mpfr\n\n"
1673"Return the second kind Bessel function of order n of x.");
1674
1675static PyObject *
1676Pympfr_yn(PyObject *self, PyObject *args)
1677{
1678    PympfrObject *result;
1679    long n = 0;
1680
1681    PARSE_ONE_MPFR_REQ_CLONG(&n, "yn() requires 'mpfr','int' arguments");
1682
1683    if (!(result = (PympfrObject*)Pympfr_new(0)))
1684        goto done;
1685
1686    mpfr_clear_flags();
1687    result->rc = mpfr_yn(result->f, n, Pympfr_AS_MPFR(self),
1688                         context->ctx.mpfr_round);
1689    MPFR_CLEANUP_SELF("yn()");
1690}
1691
1692PyDoc_STRVAR(doc_g_mpfr_ai,
1693"ai(x) -> mpfr\n\n"
1694"Return Airy function of x.");
1695
1696MPFR_UNIOP(ai)
1697
1698static PyObject *
1699Pympfr_add_fast(PyObject *x, PyObject *y)
1700{
1701    PympfrObject *result;
1702
1703    if (Pympfr_CheckAndExp(x) && Pympfr_CheckAndExp(y)) {
1704        if (!(result = (PympfrObject*)Pympfr_new(0))) {
1705            return NULL;
1706        }
1707        mpfr_clear_flags();
1708        result->rc = mpfr_add(result->f,
1709                              Pympfr_AS_MPFR(x),
1710                              Pympfr_AS_MPFR(y),
1711                              context->ctx.mpfr_round);
1712        MPFR_CLEANUP_RESULT("addition");
1713        return (PyObject*)result;
1714    }
1715    else {
1716        return Pybasic_add(x, y);
1717    }
1718}
1719
1720static PyObject *
1721Pympfr_add(PyObject *self, PyObject *args)
1722{
1723    PympfrObject *result;
1724    PyObject *other;
1725
1726    PARSE_TWO_MPFR_ARGS(other, "add() requires 'mpfr','mpfr' arguments");
1727
1728    if (!(result = (PympfrObject*)Pympfr_new(0)))
1729        goto done;
1730
1731    mpfr_clear_flags();
1732    result->rc = mpfr_add(result->f, Pympfr_AS_MPFR(self),
1733                          Pympfr_AS_MPFR(other), context->ctx.mpfr_round);
1734    MPFR_CLEANUP_SELF_OTHER("add()");
1735}
1736
1737static PyObject *
1738Pympfr_sub_fast(PyObject *x, PyObject *y)
1739{
1740    PympfrObject *result;
1741
1742    if (Pympfr_CheckAndExp(x) && Pympfr_CheckAndExp(y)) {
1743        if (!(result = (PympfrObject*)Pympfr_new(0))) {
1744            return NULL;
1745        }
1746        mpfr_clear_flags();
1747        result->rc = mpfr_sub(result->f,
1748                              Pympfr_AS_MPFR(x),
1749                              Pympfr_AS_MPFR(y),
1750                              context->ctx.mpfr_round);
1751        MPFR_CLEANUP_RESULT("subtraction");
1752        return (PyObject*)result;
1753    }
1754    else {
1755        return Pybasic_sub(x, y);
1756    }
1757}
1758
1759static PyObject *
1760Pympfr_sub(PyObject *self, PyObject *args)
1761{
1762    PympfrObject *result;
1763    PyObject *other;
1764
1765    PARSE_TWO_MPFR_ARGS(other, "sub() requires 'mpfr','mpfr' arguments");
1766
1767    if (!(result = (PympfrObject*)Pympfr_new(0)))
1768        goto done;
1769
1770    mpfr_clear_flags();
1771    result->rc = mpfr_sub(result->f, Pympfr_AS_MPFR(self),
1772                          Pympfr_AS_MPFR(other), context->ctx.mpfr_round);
1773    MPFR_CLEANUP_SELF_OTHER("sub()");
1774}
1775
1776static PyObject *
1777Pympfr_mul_fast(PyObject *x, PyObject *y)
1778{
1779    PympfrObject *result;
1780
1781    if (Pympfr_CheckAndExp(x) && Pympfr_CheckAndExp(y)) {
1782        if (!(result = (PympfrObject*)Pympfr_new(0))) {
1783            return NULL;
1784        }
1785        mpfr_clear_flags();
1786        result->rc = mpfr_mul(result->f,
1787                              Pympfr_AS_MPFR(x),
1788                              Pympfr_AS_MPFR(y),
1789                              context->ctx.mpfr_round);
1790        MPFR_CLEANUP_RESULT("multiplication");
1791        return (PyObject*)result;
1792    }
1793    else {
1794        return Pybasic_mul(x, y);
1795    }
1796}
1797
1798static PyObject *
1799Pympfr_mul(PyObject *self, PyObject *args)
1800{
1801    PympfrObject *result;
1802    PyObject *other;
1803
1804    PARSE_TWO_MPFR_ARGS(other, "mul() requires 'mpfr','mpfr' arguments");
1805
1806    if (!(result = (PympfrObject*)Pympfr_new(0)))
1807        goto done;
1808
1809    mpfr_clear_flags();
1810    result->rc = mpfr_mul(result->f, Pympfr_AS_MPFR(self),
1811                          Pympfr_AS_MPFR(other), context->ctx.mpfr_round);
1812    MPFR_CLEANUP_SELF_OTHER("mul()");
1813}
1814
1815static PyObject *
1816Pympfr_truediv_fast(PyObject *x, PyObject *y)
1817{
1818    PympfrObject *result;
1819
1820    if (Pympfr_CheckAndExp(x) && Pympfr_CheckAndExp(y)) {
1821        if (!(result = (PympfrObject*)Pympfr_new(0))) {
1822            return NULL;
1823        }
1824        mpfr_clear_flags();
1825        result->rc = mpfr_div(result->f,
1826                              Pympfr_AS_MPFR(x),
1827                              Pympfr_AS_MPFR(y),
1828                              context->ctx.mpfr_round);
1829        MPFR_CLEANUP_RESULT("division");
1830        return (PyObject*)result;
1831    }
1832    else {
1833        return Pybasic_truediv(x, y);
1834    }
1835}
1836
1837#ifdef PY2
1838static PyObject *
1839Pympfr_div2_fast(PyObject *x, PyObject *y)
1840{
1841    PympfrObject *result;
1842
1843    if (Pympfr_CheckAndExp(x) && Pympfr_CheckAndExp(y)) {
1844        if (!(result = (PympfrObject*)Pympfr_new(0))) {
1845            return NULL;
1846        }
1847        mpfr_clear_flags();
1848        result->rc = mpfr_div(result->f,
1849                              Pympfr_AS_MPFR(x),
1850                              Pympfr_AS_MPFR(y),
1851                              context->ctx.mpfr_round);
1852        MPFR_CLEANUP_RESULT("division");
1853        return (PyObject*)result;
1854    }
1855    else {
1856        return Pybasic_div2(x, y);
1857    }
1858}
1859#endif
1860
1861static PyObject *
1862Pympfr_div(PyObject *self, PyObject *args)
1863{
1864    PympfrObject *result;
1865    PyObject *other;
1866
1867    PARSE_TWO_MPFR_ARGS(other, "div() requires 'mpfr','mpfr' arguments");
1868
1869    if (!(result = (PympfrObject*)Pympfr_new(0)))
1870        goto done;
1871
1872    mpfr_clear_flags();
1873    result->rc = mpfr_div(result->f, Pympfr_AS_MPFR(self),
1874                          Pympfr_AS_MPFR(other), context->ctx.mpfr_round);
1875    MPFR_CLEANUP_SELF_OTHER("div()");
1876}
1877
1878PyDoc_STRVAR(doc_g_mpfr_fmod,
1879"fmod(x, y) -> mpfr\n\n"
1880"Return x - n*y where n is the integer quotient of x/y, rounded to 0.");
1881
1882static PyObject *
1883Pympfr_fmod(PyObject *self, PyObject *args)
1884{
1885    PympfrObject *result;
1886    PyObject *other;
1887
1888    PARSE_TWO_MPFR_ARGS(other, "fmod() requires 'mpfr','mpfr' arguments");
1889
1890    if (!(result = (PympfrObject*)Pympfr_new(0)))
1891        goto done;
1892
1893    mpfr_clear_flags();
1894    result->rc = mpfr_fmod(result->f, Pympfr_AS_MPFR(self),
1895                           Pympfr_AS_MPFR(other), context->ctx.mpfr_round);
1896    MPFR_CLEANUP_SELF_OTHER("fmod()");
1897}
1898
1899PyDoc_STRVAR(doc_g_mpfr_remainder,
1900"remainder(x, y) -> mpfr\n\n"
1901"Return x - n*y where n is the integer quotient of x/y, rounded to\n"
1902"the nearest integer and ties rounded to even.");
1903
1904static PyObject *
1905Pympfr_remainder(PyObject *self, PyObject *args)
1906{
1907    PympfrObject *result;
1908    PyObject *other;
1909
1910    PARSE_TWO_MPFR_ARGS(other, "remainder() requires 'mpfr','mpfr' arguments");
1911
1912    if (!(result = (PympfrObject*)Pympfr_new(0)))
1913        goto done;
1914
1915    mpfr_clear_flags();
1916    result->rc = mpfr_remainder(result->f, Pympfr_AS_MPFR(self),
1917                                Pympfr_AS_MPFR(other), context->ctx.mpfr_round);
1918    MPFR_CLEANUP_SELF_OTHER("remainder()");
1919}
1920
1921PyDoc_STRVAR(doc_g_mpfr_remquo,
1922"remquo(x, y) -> (mpfr, int)\n\n"
1923"Return a tuple containing the remainder(x,y) and the low bits of the\n"
1924"quotient.");
1925
1926static PyObject *
1927Pympfr_remquo(PyObject* self, PyObject *args)
1928{
1929    PyObject *result, *other;
1930    PympfrObject *value;
1931    long quobits = 0;
1932
1933    PARSE_TWO_MPFR_ARGS(other, "remquo() requires 'mpfr', 'mpfr' argument");
1934
1935    value = (PympfrObject*)Pympfr_new(0);
1936    result = PyTuple_New(2);
1937    if (!value || !result)
1938        goto done;
1939
1940    mpfr_clear_flags();
1941    value->rc = mpfr_remquo(value->f, &quobits, Pympfr_AS_MPFR(self),
1942                            Pympfr_AS_MPFR(other), context->ctx.mpfr_round);
1943    SUBNORMALIZE(value);
1944    MERGE_FLAGS;
1945    CHECK_FLAGS("remquo()");
1946
1947  done:
1948    Py_DECREF(self);
1949    Py_DECREF(other);
1950    if (PyErr_Occurred()) {
1951        Py_XDECREF(result);
1952        Py_XDECREF((PyObject*)value);
1953        result = NULL;
1954    }
1955    else {
1956        PyTuple_SET_ITEM(result, 0, (PyObject*)value);
1957        PyTuple_SET_ITEM(result, 1, PyIntOrLong_FromLong(quobits));
1958    }
1959    return result;
1960}
1961
1962PyDoc_STRVAR(doc_g_mpfr_frexp,
1963"frexp(x) -> (int, mpfr)\n\n"
1964"Return a tuple containing the exponent and mantissa of x.");
1965
1966static PyObject *
1967Pympfr_frexp(PyObject *self, PyObject *other)
1968{
1969    PyObject *result;
1970    PympfrObject *value;
1971    mpfr_exp_t exp = 0;
1972
1973    PARSE_ONE_MPFR_OTHER("frexp() requires 'mpfr' argument");
1974
1975    value = (PympfrObject*)Pympfr_new(0);
1976    result = PyTuple_New(2);
1977    if (!value || !result)
1978        goto done;
1979
1980    mpfr_clear_flags();
1981    value->rc = mpfr_frexp(&exp, value->f, Pympfr_AS_MPFR(self),
1982                           context->ctx.mpfr_round);
1983    MERGE_FLAGS;
1984    CHECK_FLAGS("frexp()");
1985
1986  done:
1987    Py_DECREF(self);
1988    Py_DECREF(other);
1989    if (PyErr_Occurred()) {
1990        Py_XDECREF(result);
1991        Py_XDECREF((PyObject*)value);
1992        result = NULL;
1993    }
1994    else {
1995        PyTuple_SET_ITEM(result, 0, PyIntOrLong_FromSsize_t((Py_ssize_t)exp));
1996        PyTuple_SET_ITEM(result, 1, (PyObject*)value);
1997    }
1998    return result;
1999}
2000
2001PyDoc_STRVAR(doc_g_mpfr_atan2,
2002"atan2(y, x) -> mpfr\n\n"
2003"Return arc-tangent of (y/x).");
2004
2005static PyObject *
2006Pympfr_atan2(PyObject *self, PyObject *args)
2007{
2008    PympfrObject *result;
2009    PyObject *other;
2010
2011    PARSE_TWO_MPFR_ARGS(other, "atan2() requires 'mpfr','mpfr' arguments");
2012
2013    if (!(result = (PympfrObject*)Pympfr_new(0)))
2014        goto done;
2015
2016    mpfr_clear_flags();
2017    result->rc = mpfr_atan2(result->f, Pympfr_AS_MPFR(self),
2018                            Pympfr_AS_MPFR(other), context->ctx.mpfr_round);
2019    MPFR_CLEANUP_SELF_OTHER("atan2()");
2020}
2021
2022PyDoc_STRVAR(doc_g_mpfr_agm,
2023"agm(x, y) -> mpfr\n\n"
2024"Return arithmetic-geometric mean of x and y.");
2025
2026static PyObject *
2027Pympfr_agm(PyObject *self, PyObject *args)
2028{
2029    PympfrObject *result;
2030    PyObject *other;
2031
2032    PARSE_TWO_MPFR_ARGS(other, "agm() requires 'mpfr','mpfr' arguments");
2033
2034    if (!(result = (PympfrObject*)Pympfr_new(0)))
2035        goto done;
2036
2037    mpfr_clear_flags();
2038    result->rc = mpfr_agm(result->f, Pympfr_AS_MPFR(self),
2039                          Pympfr_AS_MPFR(other), context->ctx.mpfr_round);
2040    MPFR_CLEANUP_SELF_OTHER("agm()");
2041}
2042
2043PyDoc_STRVAR(doc_g_mpfr_hypot,
2044"hypot(y, x) -> mpfr\n\n"
2045"Return square root of (x**2 + y**2).");
2046
2047static PyObject *
2048Pympfr_hypot(PyObject *self, PyObject *args)
2049{
2050    PympfrObject *result;
2051    PyObject *other;
2052
2053    PARSE_TWO_MPFR_ARGS(other, "hypot() requires 'mpfr','mpfr' arguments");
2054
2055    if (!(result = (PympfrObject*)Pympfr_new(0)))
2056        goto done;
2057
2058    mpfr_clear_flags();
2059    result->rc = mpfr_hypot(result->f, Pympfr_AS_MPFR(self),
2060                            Pympfr_AS_MPFR(other), context->ctx.mpfr_round);
2061    MPFR_CLEANUP_SELF_OTHER("hypot()");
2062}
2063
2064PyDoc_STRVAR(doc_g_mpfr_max2,
2065"max2(x, y) -> mpfr\n\n"
2066"Return the maximum number of x and y. This function is deprecated.\n"
2067"Please use maxnum() instead.");
2068
2069PyDoc_STRVAR(doc_g_mpfr_maxnum,
2070"maxnum(x, y) -> mpfr\n\n"
2071"Return the maximum number of x and y. If x and y are not 'mpfr', they are\n"
2072"converted to 'mpfr'. The result is rounded to match the current\n"
2073"context. If only one of x or y is a number, then that number is returned.");
2074
2075static PyObject *
2076Pympfr_max2(PyObject *self, PyObject *args)
2077{
2078    PympfrObject *result;
2079    PyObject *other;
2080
2081    PARSE_TWO_MPFR_ARGS(other, "max2() requires 'mpfr','mpfr' arguments");
2082
2083    if (!(result = (PympfrObject*)Pympfr_new(0)))
2084        goto done;
2085
2086    mpfr_clear_flags();
2087    result->rc = mpfr_max(result->f, Pympfr_AS_MPFR(self),
2088                          Pympfr_AS_MPFR(other), context->ctx.mpfr_round);
2089    MPFR_CLEANUP_SELF_OTHER("max2()");
2090}
2091
2092PyDoc_STRVAR(doc_g_mpfr_min2,
2093"min2(x, y) -> mpfr\n\n"
2094"Return the minimum of x and y. This function is deprecated.\n"
2095"Please use minnum() instead.");
2096
2097PyDoc_STRVAR(doc_g_mpfr_minnum,
2098"minnum(x, y) -> mpfr\n\n"
2099"Return the minimum of x and y. If x and y are not 'mpfr', they are\n"
2100"converted to 'mpfr'. The result is rounded to match the current\n"
2101"context. If only one of x or y is a number, then that number is returned.");
2102
2103static PyObject *
2104Pympfr_min2(PyObject *self, PyObject *args)
2105{
2106    PympfrObject *result;
2107    PyObject *other;
2108
2109    PARSE_TWO_MPFR_ARGS(other, "min2() requires 'mpfr','mpfr' arguments");
2110
2111    if (!(result = (PympfrObject*)Pympfr_new(0)))
2112        goto done;
2113
2114    mpfr_clear_flags();
2115    result->rc = mpfr_min(result->f, Pympfr_AS_MPFR(self),
2116                          Pympfr_AS_MPFR(other), context->ctx.mpfr_round);
2117    MPFR_CLEANUP_SELF_OTHER("min2()");
2118}
2119
2120PyDoc_STRVAR(doc_g_mpfr_nexttoward,
2121"next_toward(y, x) -> mpfr\n\n"
2122"Return the next 'mpfr' from x in the direction of y.");
2123
2124static PyObject *
2125Pympfr_nexttoward(PyObject *self, PyObject *args)
2126{
2127    PympfrObject *result;
2128    PyObject *other;
2129
2130    PARSE_TWO_MPFR_ARGS(other, "next_toward() requires 'mpfr','mpfr' arguments");
2131
2132    if (!(result = (PympfrObject*)Pympfr_new(mpfr_get_prec(Pympfr_AS_MPFR(self)))))
2133        goto done;
2134
2135    mpfr_clear_flags();
2136    mpfr_set(result->f, Pympfr_AS_MPFR(self), context->ctx.mpfr_round);
2137    mpfr_nexttoward(result->f, Pympfr_AS_MPFR(other));
2138    result->rc = 0;
2139    MPFR_CLEANUP_SELF_OTHER("next_toward()");
2140}
2141
2142PyDoc_STRVAR(doc_g_mpfr_nextabove,
2143"next_above(x) -> mpfr\n\n"
2144"Return the next 'mpfr' from x toward +Infinity.");
2145
2146static PyObject *
2147Pympfr_nextabove(PyObject *self, PyObject *other)
2148{
2149    PympfrObject *result;
2150
2151    PARSE_ONE_MPFR_OTHER("next_above() requires 'mpfr' argument");
2152
2153    if (!(result = (PympfrObject*)Pympfr_new(mpfr_get_prec(Pympfr_AS_MPFR(self)))))
2154        goto done;
2155
2156    mpfr_clear_flags();
2157    mpfr_set(result->f, Pympfr_AS_MPFR(self), context->ctx.mpfr_round);
2158    mpfr_nextabove(result->f);
2159    result->rc = 0;
2160    MPFR_CLEANUP_SELF("next_above()");
2161}
2162
2163PyDoc_STRVAR(doc_g_mpfr_nextbelow,
2164"next_below(x) -> mpfr\n\n"
2165"Return the next 'mpfr' from x toward -Infinity.");
2166
2167static PyObject *
2168Pympfr_nextbelow(PyObject *self, PyObject *other)
2169{
2170    PympfrObject *result;
2171
2172    PARSE_ONE_MPFR_OTHER("next_below() requires 'mpfr' argument");
2173
2174    if (!(result = (PympfrObject*)Pympfr_new(mpfr_get_prec(Pympfr_AS_MPFR(self)))))
2175        goto done;
2176
2177    mpfr_clear_flags();
2178    mpfr_set(result->f, Pympfr_AS_MPFR(self), context->ctx.mpfr_round);
2179    mpfr_nextbelow(result->f);
2180    result->rc = 0;
2181    MPFR_CLEANUP_SELF("next_below()");
2182}
2183
2184static PyObject *
2185Pympfr_sin_cos(PyObject *self, PyObject *other)
2186{
2187    PympfrObject *s, *c;
2188    PyObject *result;
2189    int code;
2190
2191    PARSE_ONE_MPFR_OTHER("sin_cos() requires 'mpfr' argument");
2192
2193    s = (PympfrObject*)Pympfr_new(0);
2194    c = (PympfrObject*)Pympfr_new(0);
2195    result = PyTuple_New(2);
2196    if (!s || !c || !result)
2197        goto done;
2198
2199    mpfr_clear_flags();
2200    code = mpfr_sin_cos(s->f, c->f, Pympfr_AS_MPFR(self),
2201                        context->ctx.mpfr_round);
2202    s->rc = code & 0x03;
2203    c->rc = code >> 2;
2204    if (s->rc == 2) s->rc = -1;
2205    if (c->rc == 2) c->rc = -1;
2206    SUBNORMALIZE(s);
2207    SUBNORMALIZE(c);
2208    MERGE_FLAGS;
2209    CHECK_FLAGS("sin_cos()");
2210
2211  done:
2212    Py_DECREF(self);
2213    if (PyErr_Occurred()) {
2214        Py_XDECREF((PyObject*)s);
2215        Py_XDECREF((PyObject*)c);
2216        Py_XDECREF(result);
2217        result = NULL;
2218    }
2219    else {
2220        PyTuple_SET_ITEM(result, 0, (PyObject*)s);
2221        PyTuple_SET_ITEM(result, 1, (PyObject*)c);
2222    }
2223    return result;
2224}
2225
2226PyDoc_STRVAR(doc_g_mpfr_sinh_cosh,
2227"sinh_cosh(x) -> (mpfr, mpfr)\n\n"
2228"Return a tuple containing the hyperbolic sine and cosine of x.");
2229
2230static PyObject *
2231Pympfr_sinh_cosh(PyObject *self, PyObject *other)
2232{
2233    PympfrObject *s, *c;
2234    PyObject *result;
2235    int code;
2236
2237    PARSE_ONE_MPFR_OTHER("sinh_cosh() requires 'mpfr' argument");
2238
2239    s = (PympfrObject*)Pympfr_new(0);
2240    c = (PympfrObject*)Pympfr_new(0);
2241    result = PyTuple_New(2);
2242    if (!s || !c || !result)
2243        goto done;
2244
2245    mpfr_clear_flags();
2246    code = mpfr_sinh_cosh(s->f, c->f, Pympfr_AS_MPFR(self),
2247                          context->ctx.mpfr_round);
2248    s->rc = code & 0x03;
2249    c->rc = code >> 2;
2250    if (s->rc == 2) s->rc = -1;
2251    if (c->rc == 2) c->rc = -1;
2252    SUBNORMALIZE(s);
2253    SUBNORMALIZE(c);
2254    MERGE_FLAGS;
2255    CHECK_FLAGS("sin_cos()");
2256
2257  done:
2258    Py_DECREF(self);
2259    if (PyErr_Occurred()) {
2260        Py_XDECREF((PyObject*)s);
2261        Py_XDECREF((PyObject*)c);
2262        Py_XDECREF(result);
2263        result = NULL;
2264    }
2265    else {
2266        PyTuple_SET_ITEM(result, 0, (PyObject*)s);
2267        PyTuple_SET_ITEM(result, 1, (PyObject*)c);
2268    }
2269    return result;
2270}
2271
2272static PyObject *
2273Pympfr_fma(PyObject *self, PyObject *args)
2274{
2275    PympfrObject *result, *x, *y, *z;
2276
2277    if (PyTuple_GET_SIZE(args) != 3) {
2278        TYPE_ERROR("fma() requires 'mpfr','mpfr','mpfr' arguments.");
2279        return NULL;
2280    }
2281
2282    result = (PympfrObject*)Pympfr_new(0);
2283    x = Pympfr_From_Real(PyTuple_GET_ITEM(args, 0), 0);
2284    y = Pympfr_From_Real(PyTuple_GET_ITEM(args, 1), 0);
2285    z = Pympfr_From_Real(PyTuple_GET_ITEM(args, 2), 0);
2286    if (!result || !x || !y || !z) {
2287        TYPE_ERROR("fma() requires 'mpfr','mpfr','mpfr' arguments.");
2288        goto done;
2289    }
2290
2291    mpfr_clear_flags();
2292    result->rc = mpfr_fma(result->f, x->f, y->f, z->f,
2293                          context->ctx.mpfr_round);
2294    SUBNORMALIZE(result);
2295    MERGE_FLAGS;
2296    CHECK_FLAGS("fma()");
2297
2298  done:
2299    Py_XDECREF((PyObject*)x);
2300    Py_XDECREF((PyObject*)y);
2301    Py_XDECREF((PyObject*)z);
2302    if (PyErr_Occurred()) {
2303        Py_XDECREF(result);
2304        result = NULL;
2305    }
2306    return (PyObject*)result;
2307}
2308
2309static PyObject *
2310Pympfr_fms(PyObject *self, PyObject *args)
2311{
2312    PympfrObject *result, *x, *y, *z;
2313
2314    if (PyTuple_GET_SIZE(args) != 3) {
2315        TYPE_ERROR("fms() requires 'mpfr','mpfr','mpfr' arguments.");
2316        return NULL;
2317    }
2318
2319    result = (PympfrObject*)Pympfr_new(0);
2320    x = Pympfr_From_Real(PyTuple_GET_ITEM(args, 0), 0);
2321    y = Pympfr_From_Real(PyTuple_GET_ITEM(args, 1), 0);
2322    z = Pympfr_From_Real(PyTuple_GET_ITEM(args, 2), 0);
2323    if (!result || !x || !y || !z) {
2324        TYPE_ERROR("fms() requires 'mpfr','mpfr','mpfr' arguments.");
2325        goto done;
2326    }
2327
2328    mpfr_clear_flags();
2329    result->rc = mpfr_fms(result->f, x->f, y->f, z->f,
2330                          context->ctx.mpfr_round);
2331    SUBNORMALIZE(result);
2332    MERGE_FLAGS;
2333    CHECK_FLAGS("fms()");
2334
2335  done:
2336    Py_XDECREF((PyObject*)x);
2337    Py_XDECREF((PyObject*)y);
2338    Py_XDECREF((PyObject*)z);
2339    if (PyErr_Occurred()) {
2340        Py_XDECREF(result);
2341        result = NULL;
2342    }
2343    return (PyObject*)result;
2344}
2345
2346PyDoc_STRVAR(doc_g_mpfr_factorial,
2347"factorial(n) -> mpfr\n\n"
2348"Return the floating-point approximation to the factorial of n.\n\n"
2349"See fac(n) to get the exact integer result.");
2350
2351static PyObject *
2352Pympfr_factorial(PyObject *self, PyObject *other)
2353{
2354    PympfrObject *result;
2355    long n;
2356
2357    n = clong_From_Integer(other);
2358    if ((n == -1) && PyErr_Occurred()) {
2359        TYPE_ERROR("factorial() requires 'int' argument");
2360        return NULL;
2361    }
2362
2363    if (n < 0) {
2364        VALUE_ERROR("factorial() of negative number");
2365        return NULL;
2366    }
2367
2368    if (!(result = (PympfrObject*)Pympfr_new(0)))
2369        return NULL;
2370
2371    mpfr_clear_flags();
2372    mpfr_fac_ui(result->f, n, context->ctx.mpfr_round);
2373
2374    MERGE_FLAGS;
2375    CHECK_FLAGS("factorial()");
2376  done:
2377    return (PyObject*)result;
2378}
2379
2380PyDoc_STRVAR(doc_g_mpfr_is_lessgreater,
2381"is_lessgreater(x,y) -> boolean\n\n"
2382"Return True if x > y or x < y. Return False if x == y or either x\n"
2383"and/or y is NaN.");
2384
2385static PyObject *
2386Pympfr_is_lessgreater(PyObject *self, PyObject *args)
2387{
2388    PyObject *other;
2389    int temp;
2390
2391    PARSE_TWO_MPFR_ARGS(other, "is_lessgreater() requires 'mpfr','mpfr' arguments");
2392
2393    temp = mpfr_lessgreater_p(Pympfr_AS_MPFR(self), Pympfr_AS_MPFR(other));
2394    Py_DECREF(self);
2395    Py_DECREF(other);
2396    if (temp)
2397        Py_RETURN_TRUE;
2398    else
2399        Py_RETURN_FALSE;
2400}
2401
2402PyDoc_STRVAR(doc_g_mpfr_is_unordered,
2403"is_unordered(x,y) -> boolean\n\n"
2404"Return True if either x and/or y is NaN.");
2405
2406static PyObject *
2407Pympfr_is_unordered(PyObject *self, PyObject *args)
2408{
2409    PyObject *other;
2410    int temp;
2411
2412    PARSE_TWO_MPFR_ARGS(other, "unordered() requires 'mpfr','mpfr' arguments");
2413
2414    temp = mpfr_unordered_p(Pympfr_AS_MPFR(self), Pympfr_AS_MPFR(other));
2415    Py_DECREF(self);
2416    Py_DECREF(other);
2417    if (temp)
2418        Py_RETURN_TRUE;
2419    else
2420        Py_RETURN_FALSE;
2421}
2422
2423PyDoc_STRVAR(doc_g_mpfr_check_range,
2424"check_range(x) -> mpfr\n\n"
2425"Return a new 'mpfr' with exponent that lies within the current range\n"
2426"of emin and emax.");
2427
2428static PyObject *
2429Pympfr_check_range(PyObject *self, PyObject *other)
2430{
2431    PympfrObject *result = NULL;
2432
2433    if (self && Pympfr_Check(self)) {
2434        if ((result = (PympfrObject*)Pympfr_new(mpfr_get_prec(Pympfr_AS_MPFR(self))))) {
2435            mpfr_set(result->f, Pympfr_AS_MPFR(self), context->ctx.mpfr_round);
2436            result->round_mode = ((PympfrObject*)self)->round_mode;
2437            result->rc = ((PympfrObject*)self)->rc;
2438            mpfr_clear_flags();
2439            result->rc = mpfr_check_range(result->f, result->rc,
2440                                          result->round_mode);
2441        }
2442    }
2443    else if (Pympfr_Check(other)) {
2444        if ((result = (PympfrObject*)Pympfr_new(mpfr_get_prec(Pympfr_AS_MPFR(other))))) {
2445            mpfr_set(result->f, Pympfr_AS_MPFR(other), context->ctx.mpfr_round);
2446            result->round_mode = ((PympfrObject*)other)->round_mode;
2447            result->rc = ((PympfrObject*)other)->rc;
2448            mpfr_clear_flags();
2449            result->rc = mpfr_check_range(result->f, result->rc,
2450                                          result->round_mode);
2451        }
2452    }
2453    else {
2454        TYPE_ERROR("check_range() requires 'mpfr' argument");
2455    }
2456    MERGE_FLAGS;
2457    CHECK_FLAGS("check_range()");
2458  done:
2459    return (PyObject*)result;
2460}
2461
2462PyDoc_STRVAR(doc_g_mpfr_fsum,
2463"fsum(iterable) -> mpfr\n\n"
2464"Return an accurate sum of the values in the iterable.");
2465
2466static PyObject *
2467Pympfr_fsum(PyObject *self, PyObject *other)
2468{
2469    PympfrObject *temp, *result;
2470    mpfr_ptr *tab;
2471    int errcode;
2472    Py_ssize_t i, seq_length = 0;
2473
2474    if (!(result = (PympfrObject*)Pympfr_new(0)))
2475        return NULL;
2476
2477    if (!(other = PySequence_List(other))) {
2478        Py_DECREF((PyObject*)result);
2479        TYPE_ERROR("argument must be an iterable");
2480        return NULL;
2481    }
2482
2483    /* other contains a new list containing all the values from the
2484     * iterable. Now make sure each item in the list is an mpfr.
2485     */
2486
2487    seq_length = PyList_GET_SIZE(other);
2488    for (i=0; i < seq_length; i++) {
2489        if (!(temp = Pympfr_From_Real(PyList_GET_ITEM(other, i), 0))) {
2490            Py_DECREF(other);
2491            Py_DECREF((PyObject*)result);
2492            TYPE_ERROR("all items in iterable must be real numbers");
2493            return NULL;
2494        }
2495
2496        errcode = PyList_SetItem(other, i,(PyObject*)temp);
2497        if (errcode < 0) {
2498            Py_DECREF(other);
2499            Py_DECREF((PyObject*)result);
2500            TYPE_ERROR("all items in iterable must be real numbers");
2501            return NULL;
2502        }
2503    }
2504
2505    /* create an array of pointers to the mpfr_t field of a Pympfr object */
2506
2507    if (!(tab = (mpfr_ptr *)GMPY_MALLOC((sizeof(mpfr_srcptr) * seq_length)))) {
2508        Py_DECREF(other);
2509        Py_DECREF((PyObject*)result);
2510        return PyErr_NoMemory();
2511    }
2512    for (i=0; i < seq_length; i++) {
2513        temp = (PympfrObject*)PyList_GET_ITEM(other, i);
2514        tab[i] = temp->f;
2515    }
2516    result->rc = mpfr_sum(result->f, tab, seq_length, context->ctx.mpfr_round);
2517    Py_DECREF(other);
2518    GMPY_FREE(tab);
2519
2520    return (PyObject*)result;
2521}
2522
2523PyDoc_STRVAR(doc_g_mpfr_degrees,
2524"degrees(x) -> mpfr\n\n"
2525"Convert angle x from radians to degrees.");
2526
2527static PyObject *
2528Pympfr_degrees(PyObject *self, PyObject *other)
2529{
2530    PympfrObject *result, *temp;
2531
2532    PARSE_ONE_MPFR_OTHER("degrees() requires 'mpfr' argument");
2533
2534    result = (PympfrObject*)Pympfr_new(0);
2535    temp = (PympfrObject*)Pympfr_new(context->ctx.mpfr_prec + 20);
2536    if (!result || !temp) {
2537        Py_XDECREF((PyObject*)temp);
2538        Py_XDECREF((PyObject*)result);
2539        Py_DECREF(other);
2540        return NULL;
2541    }
2542
2543    mpfr_clear_flags();
2544    mpfr_const_pi(temp->f, MPFR_RNDN);
2545    mpfr_ui_div(temp->f, 180, temp->f, MPFR_RNDN);
2546    mpfr_mul(result->f, temp->f, Pympfr_AS_MPFR(self), MPFR_RNDN);
2547    Py_DECREF((PyObject*)temp);
2548    MPFR_CLEANUP_SELF("degrees()");
2549}
2550
2551PyDoc_STRVAR(doc_g_mpfr_radians,
2552"radians(x) -> mpfr\n\n"
2553"Convert angle x from degrees to radians.");
2554
2555static PyObject *
2556Pympfr_radians(PyObject *self, PyObject *other)
2557{
2558    PympfrObject *result, *temp;
2559
2560    PARSE_ONE_MPFR_OTHER("radians() requires 'mpfr' argument");
2561
2562    result = (PympfrObject*)Pympfr_new(0);
2563    temp = (PympfrObject*)Pympfr_new(context->ctx.mpfr_prec + 20);
2564    if (!result || !temp) {
2565        Py_XDECREF((PyObject*)temp);
2566        Py_XDECREF((PyObject*)result);
2567        Py_DECREF(other);
2568        return NULL;
2569    }
2570
2571    mpfr_clear_flags();
2572    mpfr_const_pi(temp->f, MPFR_RNDN);
2573    mpfr_div_ui(temp->f, temp->f, 180, MPFR_RNDN);
2574    mpfr_mul(result->f, Pympfr_AS_MPFR(self), temp->f, MPFR_RNDN);
2575    Py_DECREF((PyObject*)temp);
2576    MPFR_CLEANUP_SELF("radians()");
2577}
2578
2579PyDoc_STRVAR(doc_mpfr_format,
2580"x.__format__(fmt) -> string\n\n"
2581"Return a Python string by formatting 'x' using the format string\n"
2582"'fmt'. A valid format string consists of:\n"
2583"     optional alignment code:\n"
2584"        '<' -> left shifted in field\n"
2585"        '>' -> right shifted in field\n"
2586"        '^' -> centered in field\n"
2587"     optional leading sign code\n"
2588"        '+' -> always display leading sign\n"
2589"        '-' -> only display minus for negative values\n"
2590"        ' ' -> minus for negative values, space for positive values\n"
2591"     optional width.precision\n"
2592"     optional rounding mode:\n"
2593"        'U' -> round toward plus Infinity\n"
2594"        'D' -> round toward minus Infinity\n"
2595"        'Y' -> round away from zero\n"
2596"        'Z' -> round toward zero\n"
2597"        'N' -> round to nearest\n"
2598"     optional conversion code:\n"
2599"        'a','A' -> hex format\n"
2600"        'b'     -> binary format\n"
2601"        'e','E' -> scientific format\n"
2602"        'f','F' -> fixed point format\n"
2603"        'g','G' -> fixed or float format\n\n"
2604"The default format is '.6f'.");
2605
2606static PyObject *
2607Pympfr_format(PyObject *self, PyObject *args)
2608{
2609    PyObject *result = 0, *mpfrstr = 0;
2610    char *buffer = 0, *newbuf = 0, *fmtcode = 0, *p1, *p2, *p3;
2611    char mpfrfmt[100], fmt[30];
2612    int buflen;
2613    int seensign = 0, seenalign = 0, seendecimal = 0, seendigits = 0;
2614    int seenround = 0, seenconv = 0;
2615
2616    if (!Pympfr_Check(self)) {
2617        TYPE_ERROR("requires mpfr type");
2618        return NULL;
2619    }
2620
2621    if (!PyArg_ParseTuple(args, "s", &fmtcode))
2622        return NULL;
2623
2624    p2 = mpfrfmt;
2625    p3 = fmt;
2626    *(p2++) = '%';
2627
2628    for (p1 = fmtcode; *p1 != '\00'; p1++) {
2629        if (*p1 == '<' || *p1 == '>' || *p1 == '^') {
2630            if (seenalign || seensign || seendecimal || seendigits || seenround) {
2631                VALUE_ERROR("Invalid conversion specification");
2632                return NULL;
2633            }
2634            else {
2635                *(p3++) = *p1;
2636                seenalign = 1;
2637                continue;
2638            }
2639        }
2640        if (*p1 == '+' || *p1 == ' ') {
2641            if (seensign || seendecimal || seendigits || seenround) {
2642                VALUE_ERROR("Invalid conversion specification");
2643                return NULL;
2644            }
2645            else {
2646                *(p2++) = *p1;
2647                seensign = 1;
2648                continue;
2649            }
2650        }
2651        if (*p1 == '-') {
2652            if (seensign || seendecimal || seendigits || seenround) {
2653                VALUE_ERROR("Invalid conversion specification");
2654                return NULL;
2655            }
2656            else {
2657                seensign = 1;
2658                continue;
2659            }
2660        }
2661        if (*p1 == '.') {
2662            if (seendecimal || seendigits || seenround) {
2663                VALUE_ERROR("Invalid conversion specification");
2664                return NULL;
2665            }
2666            else {
2667                *(p2++) = *p1;
2668                seendecimal = 1;
2669                continue;
2670            }
2671        }
2672        if (isdigit(*p1)) {
2673            if (seendigits || seenround) {
2674                VALUE_ERROR("Invalid conversion specification");
2675                return NULL;
2676            }
2677            else if (seendecimal) {
2678                *(p2++) = *p1;
2679                continue;
2680            }
2681            else {
2682                if (p3 == fmt) {
2683                    *(p3++) = '>';
2684                    seenalign = 1;
2685                }
2686                *(p3++) = *p1;
2687                continue;
2688            }
2689        }
2690        if (!seendigits) {
2691            seendigits = 1;
2692            *(p2++) = 'R';
2693        }
2694        if (*p1 == 'U' || *p1 == 'D' || *p1 == 'Y' || *p1 == 'Z' ||
2695            *p1 == 'N' ) {
2696            if (seenround) {
2697                VALUE_ERROR("Invalid conversion specification");
2698                return NULL;
2699            }
2700            else {
2701                *(p2++) = *p1;
2702                seenround = 1;
2703                continue;
2704            }
2705        }
2706        if (*p1 == 'a' || *p1 == 'A' || *p1 == 'b' || *p1 == 'e' ||
2707            *p1 == 'E' || *p1 == 'f' || *p1 == 'F' || *p1 == 'g' ||
2708            *p1 == 'G' ) {
2709            *(p2++) = *p1;
2710            seenconv = 1;
2711            break;
2712        }
2713        VALUE_ERROR("Invalid conversion specification");
2714        return NULL;
2715    }
2716
2717    if (!seendigits)
2718        *(p2++) = 'R';
2719    if (!seenconv)
2720        *(p2++) = 'f';
2721
2722    *(p2) = '\00';
2723    *(p3) = '\00';
2724
2725    buflen = mpfr_asprintf(&buffer, mpfrfmt, Pympfr_AS_MPFR(self));
2726
2727    /* If there isn't a decimal point in the output and the output
2728     * only consists of digits, then append .0 */
2729    if (strlen(buffer) == strspn(buffer, "+- 0123456789")) {
2730        newbuf = GMPY_MALLOC(buflen + 3);
2731        if (!newbuf) {
2732            mpfr_free_str(buffer);
2733            return PyErr_NoMemory();
2734        }
2735        *newbuf = '\0';
2736        strcat(newbuf, buffer);
2737        strcat(newbuf, ".0");
2738        mpfr_free_str(buffer);
2739        mpfrstr = Py_BuildValue("s", newbuf);
2740        GMPY_FREE(newbuf);
2741    }
2742    else {
2743        mpfrstr = Py_BuildValue("s", buffer);
2744        mpfr_free_str(buffer);
2745    }
2746    if (!mpfrstr) {
2747        return NULL;
2748    }
2749
2750    result = PyObject_CallMethod(mpfrstr, "__format__", "(s)", fmt);
2751    Py_DECREF(mpfrstr);
2752    return result;
2753}
2754
2755PyDoc_STRVAR(doc_mpfr_sizeof,
2756"x.__sizeof__()\n\n"
2757"Returns the amount of memory consumed by x.");
2758
2759static PyObject *
2760Pympfr_sizeof(PyObject *self, PyObject *other)
2761{
2762    return PyIntOrLong_FromSize_t(sizeof(PympfrObject) + \
2763        (((Pympfr_AS_MPFR(self))->_mpfr_prec + mp_bits_per_limb - 1) / \
2764        mp_bits_per_limb) * sizeof(mp_limb_t));
2765}
2766
2767#ifdef PY3
2768static PyNumberMethods mpfr_number_methods =
2769{
2770    (binaryfunc) Pympfr_add_fast,        /* nb_add                  */
2771    (binaryfunc) Pympfr_sub_fast,        /* nb_subtract             */
2772    (binaryfunc) Pympfr_mul_fast,        /* nb_multiply             */
2773    (binaryfunc) Pybasic_rem,            /* nb_remainder            */
2774    (binaryfunc) Pybasic_divmod,         /* nb_divmod               */
2775    (ternaryfunc) Pympany_pow,           /* nb_power                */
2776    (unaryfunc) Pympfr_neg,              /* nb_negative             */
2777    (unaryfunc) Pympfr_pos,              /* nb_positive             */
2778    (unaryfunc) Pympfr_abs,              /* nb_absolute             */
2779    (inquiry) Pympfr_nonzero,            /* nb_bool                 */
2780        0,                               /* nb_invert               */
2781        0,                               /* nb_lshift               */
2782        0,                               /* nb_rshift               */
2783        0,                               /* nb_and                  */
2784        0,                               /* nb_xor                  */
2785        0,                               /* nb_or                   */
2786    (unaryfunc) Pympfr_To_PyLong,        /* nb_int                  */
2787        0,                               /* nb_reserved             */
2788    (unaryfunc) Pympfr_To_PyFloat,       /* nb_float                */
2789        0,                               /* nb_inplace_add          */
2790        0,                               /* nb_inplace_subtract     */
2791        0,                               /* nb_inplace_multiply     */
2792        0,                               /* nb_inplace_remainder    */
2793        0,                               /* nb_inplace_power        */
2794        0,                               /* nb_inplace_lshift       */
2795        0,                               /* nb_inplace_rshift       */
2796        0,                               /* nb_inplace_and          */
2797        0,                               /* nb_inplace_xor          */
2798        0,                               /* nb_inplace_or           */
2799    (binaryfunc) Pybasic_floordiv,       /* nb_floor_divide         */
2800    (binaryfunc) Pympfr_truediv_fast,    /* nb_true_divide          */
2801        0,                               /* nb_inplace_floor_divide */
2802        0,                               /* nb_inplace_true_divide  */
2803        0,                               /* nb_index                */
2804};
2805#else
2806static PyNumberMethods mpfr_number_methods =
2807{
2808    (binaryfunc) Pympfr_add_fast,        /* nb_add                  */
2809    (binaryfunc) Pympfr_sub_fast,        /* nb_subtract             */
2810    (binaryfunc) Pympfr_mul_fast,        /* nb_multiply             */
2811    (binaryfunc) Pympfr_div2_fast,       /* nb_divide               */
2812    (binaryfunc) Pybasic_rem,            /* nb_remainder            */
2813    (binaryfunc) Pybasic_divmod,         /* nb_divmod               */
2814    (ternaryfunc) Pympany_pow,           /* nb_power                */
2815    (unaryfunc) Pympfr_neg,              /* nb_negative             */
2816    (unaryfunc) Pympfr_pos,              /* nb_positive             */
2817    (unaryfunc) Pympfr_abs,              /* nb_absolute             */
2818    (inquiry) Pympfr_nonzero,            /* nb_bool                 */
2819        0,                               /* nb_invert               */
2820        0,                               /* nb_lshift               */
2821        0,                               /* nb_rshift               */
2822        0,                               /* nb_and                  */
2823        0,                               /* nb_xor                  */
2824        0,                               /* nb_or                   */
2825        0,                               /* nb_coerce               */
2826    (unaryfunc) Pympfr_To_PyInt,         /* nb_int                  */
2827    (unaryfunc) Pympfr_To_PyLong,        /* nb_long                 */
2828    (unaryfunc) Pympfr_To_PyFloat,       /* nb_float                */
2829        0,                               /* nb_oct                  */
2830        0,                               /* nb_hex                  */
2831        0,                               /* nb_inplace_add          */
2832        0,                               /* nb_inplace_subtract     */
2833        0,                               /* nb_inplace_multiply     */
2834        0,                               /* nb_inplace_divide       */
2835        0,                               /* nb_inplace_remainder    */
2836        0,                               /* nb_inplace_power        */
2837        0,                               /* nb_inplace_lshift       */
2838        0,                               /* nb_inplace_rshift       */
2839        0,                               /* nb_inplace_and          */
2840        0,                               /* nb_inplace_xor          */
2841        0,                               /* nb_inplace_or           */
2842    (binaryfunc) Pybasic_floordiv,       /* nb_floor_divide         */
2843    (binaryfunc) Pympfr_truediv_fast,    /* nb_true_divide          */
2844        0,                               /* nb_inplace_floor_divide */
2845        0,                               /* nb_inplace_true_divide  */
2846};
2847#endif
2848
2849static PyGetSetDef Pympfr_getseters[] =
2850{
2851    {"precision", (getter)Pympfr_getprec_attrib, NULL, "precision in bits", NULL},
2852    {"rc", (getter)Pympfr_getrc_attrib, NULL, "return code", NULL},
2853    {"imag", (getter)Pympfr_getimag_attrib, NULL, "imaginary component", NULL},
2854    {"real", (getter)Pympfr_getreal_attrib, NULL, "real component", NULL},
2855    {NULL}
2856};
2857
2858static PyMethodDef Pympfr_methods [] =
2859{
2860    { "__ceil__", Pympfr_ceil, METH_NOARGS, doc_mpfr_ceil },
2861    { "__floor__", Pympfr_floor, METH_NOARGS, doc_mpfr_floor },
2862    { "__format__", Pympfr_format, METH_VARARGS, doc_mpfr_format },
2863    { "__round__", Pympfr_round10, METH_VARARGS, doc_g_mpfr_round10 },
2864    { "__sizeof__", Pympfr_sizeof, METH_NOARGS, doc_mpfr_sizeof },
2865    { "__trunc__", Pympfr_trunc, METH_NOARGS, doc_mpfr_trunc },
2866    { "as_integer_ratio", Pympfr_integer_ratio, METH_NOARGS, doc_mpfr_integer_ratio },
2867    { "as_mantissa_exp", Pympfr_mantissa_exp, METH_NOARGS, doc_mpfr_mantissa_exp },
2868    { "as_simple_fraction", (PyCFunction)Pympfr_simple_fraction, METH_VARARGS | METH_KEYWORDS, doc_mpfr_simple_fraction },
2869    { "conjugate", Pympfr_conjugate, METH_NOARGS, doc_mpfr_conjugate },
2870    { "digits", Pympfr_digits, METH_VARARGS, doc_mpfr_digits },
2871    { "is_integer", Pympfr_is_integer, METH_NOARGS, doc_mpfr_is_integer },
2872    { NULL, NULL, 1 }
2873};
2874
2875static PyTypeObject Pympfr_Type =
2876{
2877    /* PyObject_HEAD_INIT(&PyType_Type) */
2878#ifdef PY3
2879    PyVarObject_HEAD_INIT(NULL, 0)
2880#else
2881    PyObject_HEAD_INIT(0)
2882    0,                                      /* ob_size          */
2883#endif
2884    "mpfr",                                 /* tp_name          */
2885    sizeof(PympfrObject),                   /* tp_basicsize     */
2886        0,                                  /* tp_itemsize      */
2887    /* methods */
2888    (destructor) Pympfr_dealloc,            /* tp_dealloc       */
2889        0,                                  /* tp_print         */
2890        0,                                  /* tp_getattr       */
2891        0,                                  /* tp_setattr       */
2892        0,                                  /* tp_reserved      */
2893    (reprfunc) Pympfr_To_Repr,              /* tp_repr          */
2894    &mpfr_number_methods,                   /* tp_as_number     */
2895        0,                                  /* tp_as_sequence   */
2896        0,                                  /* tp_as_mapping    */
2897    (hashfunc) Pympfr_hash,                 /* tp_hash          */
2898        0,                                  /* tp_call          */
2899    (reprfunc) Pympfr_To_Str,               /* tp_str           */
2900    (getattrofunc) 0,                       /* tp_getattro      */
2901    (setattrofunc) 0,                       /* tp_setattro      */
2902        0,                                  /* tp_as_buffer     */
2903#ifdef PY3
2904    Py_TPFLAGS_DEFAULT,                     /* tp_flags         */
2905#else
2906    Py_TPFLAGS_HAVE_RICHCOMPARE|Py_TPFLAGS_CHECKTYPES,  /* tp_flags */
2907#endif
2908    "Multiple precision real",              /* tp_doc           */
2909        0,                                  /* tp_traverse      */
2910        0,                                  /* tp_clear         */
2911    (richcmpfunc)&mpany_richcompare,        /* tp_richcompare   */
2912        0,                                  /* tp_weaklistoffset*/
2913        0,                                  /* tp_iter          */
2914        0,                                  /* tp_iternext      */
2915    Pympfr_methods,                         /* tp_methods       */
2916        0,                                  /* tp_members       */
2917    Pympfr_getseters,                       /* tp_getset        */
2918};
2919