GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — cpython/Objects/floatobject.c at main · python/cpython Expand file tree/ Copy pathfloatobject.cMore file actions 2243 lines (1984 loc) · 63.8 KB / Copy pathfloatobject.cFile metadata and controls2243 lines (1984 loc) · 63.8 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 /* Float object implementation */ /* XXX There should be overflow checks here, but it's hard to check for any kind of float exception without losing portability. */ #include "Python.h" #include "pycore_abstract.h" // _PyNumber_Index() #include "pycore_bitutils.h" // _Py_bswap16() #include "pycore_dtoa.h" // _Py_dg_dtoa() #include "pycore_floatobject.h" // _PyFloat_FormatAdvancedWriter() #include "pycore_freelist.h" // _Py_FREELIST_FREE(), _Py_FREELIST_POP() #include "pycore_initconfig.h" // _PyStatus_OK() #include "pycore_long.h" // _PyLong_GetOne() #include "pycore_modsupport.h" // _PyArg_NoKwnames() #include "pycore_object.h" // _PyObject_Init(), _PyDebugAllocatorStats() #include "pycore_pymath.h" // _PY_SHORT_FLOAT_REPR #include "pycore_pystate.h" // _PyInterpreterState_GET() #include "pycore_stackref.h" // PyStackRef_AsPyObjectBorrow() #include "pycore_structseq.h" // _PyStructSequence_FiniBuiltin() #include "pycore_tuple.h" // _PyTuple_FromPair #include <float.h> // DBL_MAX #include <stdlib.h> // strtol() /*[clinic input] class float "PyObject *" "&PyFloat_Type" [clinic start generated code]*/ /*[clinic end generated code: output=da39a3ee5e6b4b0d input=dd0003f68f144284]*/ #include "clinic/floatobject.c.h" double PyFloat_GetMax(void) { return DBL_MAX; } double PyFloat_GetMin(void) { return DBL_MIN; } static PyTypeObject FloatInfoType; PyDoc_STRVAR(floatinfo__doc__, "sys.float_info\n\ \n\ A named tuple holding information about the float type. It contains low level\n\ information about the precision and internal representation. Please study\n\ your system's :file:`float.h` for more information."); static PyStructSequence_Field floatinfo_fields[] = { {"max", "DBL_MAX -- maximum representable finite float"}, {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) " "is representable"}, {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e " "is representable"}, {"min", "DBL_MIN -- Minimum positive normalized float"}, {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) " "is a normalized float"}, {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is " "a normalized float"}, {"dig", "DBL_DIG -- maximum number of decimal digits that " "can be faithfully represented in a float"}, {"mant_dig", "DBL_MANT_DIG -- mantissa digits"}, {"epsilon", "DBL_EPSILON -- Difference between 1 and the next " "representable float"}, {"radix", "FLT_RADIX -- radix of exponent"}, {"rounds", "FLT_ROUNDS -- rounding mode used for arithmetic " "operations"}, {0} }; static PyStructSequence_Desc floatinfo_desc = { "sys.float_info", /* name */ floatinfo__doc__, /* doc */ floatinfo_fields, /* fields */ 11 }; PyObject * PyFloat_GetInfo(void) { PyObject* floatinfo; int pos = 0; floatinfo = PyStructSequence_New(&FloatInfoType); if (floatinfo == NULL) { return NULL; } #define SetFlag(CALL) \ do { \ PyObject *flag = (CALL); \ if (flag == NULL) { \ Py_CLEAR(floatinfo); \ return NULL; \ } \ PyStructSequence_SET_ITEM(floatinfo, pos++, flag); \ } while (0) #define SetIntFlag(FLAG) SetFlag(PyLong_FromLong((FLAG))) #define SetDblFlag(FLAG) SetFlag(PyFloat_FromDouble((FLAG))) SetDblFlag(DBL_MAX); SetIntFlag(DBL_MAX_EXP); SetIntFlag(DBL_MAX_10_EXP); SetDblFlag(DBL_MIN); SetIntFlag(DBL_MIN_EXP); SetIntFlag(DBL_MIN_10_EXP); SetIntFlag(DBL_DIG); SetIntFlag(DBL_MANT_DIG); SetDblFlag(DBL_EPSILON); SetIntFlag(FLT_RADIX); SetIntFlag(FLT_ROUNDS); #undef SetIntFlag #undef SetDblFlag #undef SetFlag return floatinfo; } PyObject * PyFloat_FromDouble(double fval) { PyFloatObject *op = _Py_FREELIST_POP(PyFloatObject, floats); if (op == NULL) { op = PyObject_Malloc(sizeof(PyFloatObject)); if (!op) { return PyErr_NoMemory(); } _PyObject_Init((PyObject*)op, &PyFloat_Type); } op->ob_fval = fval; return (PyObject *) op; } static PyObject * float_from_string_inner(const char *s, Py_ssize_t len, void *obj) { double x; const char *end; const char *last = s + len; /* strip leading whitespace */ while (s < last && Py_ISSPACE(*s)) { s++; } if (s == last) { PyErr_Format(PyExc_ValueError, "could not convert string to float: " "%R", obj); return NULL; } /* strip trailing whitespace */ while (s < last - 1 && Py_ISSPACE(last[-1])) { last--; } /* We don't care about overflow or underflow. If the platform * supports them, infinities and signed zeroes (on underflow) are * fine. */ x = PyOS_string_to_double(s, (char **)&end, NULL); if (end != last) { PyErr_Format(PyExc_ValueError, "could not convert string to float: " "%R", obj); return NULL; } else if (x == -1.0 && PyErr_Occurred()) { return NULL; } else { return PyFloat_FromDouble(x); } } PyObject * PyFloat_FromString(PyObject *v) { const char *s; PyObject *s_buffer = NULL; Py_ssize_t len; Py_buffer view = {NULL, NULL}; PyObject *result = NULL; if (PyUnicode_Check(v)) { s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v); if (s_buffer == NULL) return NULL; assert(PyUnicode_IS_ASCII(s_buffer)); /* Simply get a pointer to existing ASCII characters. */ s = PyUnicode_AsUTF8AndSize(s_buffer, &len); assert(s != NULL); } else if (PyBytes_Check(v)) { s = PyBytes_AS_STRING(v); len = PyBytes_GET_SIZE(v); } else if (PyByteArray_Check(v)) { s = PyByteArray_AS_STRING(v); len = PyByteArray_GET_SIZE(v); } else if (PyObject_GetBuffer(v, &view, PyBUF_SIMPLE) == 0) { s = (const char *)view.buf; len = view.len; /* Copy to NUL-terminated buffer. */ s_buffer = PyBytes_FromStringAndSize(s, len); if (s_buffer == NULL) { PyBuffer_Release(&view); return NULL; } s = PyBytes_AS_STRING(s_buffer); } else { PyErr_Format(PyExc_TypeError, "float() argument must be a string or a real number, not '%.200s'", Py_TYPE(v)->tp_name); return NULL; } result = _Py_string_to_number_with_underscores(s, len, "float", v, v, float_from_string_inner); PyBuffer_Release(&view); Py_XDECREF(s_buffer); return result; } void _PyFloat_ExactDealloc(PyObject *obj) { assert(PyFloat_CheckExact(obj)); _Py_FREELIST_FREE(floats, obj, PyObject_Free); } static void float_dealloc(PyObject *op) { assert(PyFloat_Check(op)); if (PyFloat_CheckExact(op)) _PyFloat_ExactDealloc(op); else Py_TYPE(op)->tp_free(op); } double PyFloat_AsDouble(PyObject *op) { PyNumberMethods *nb; PyObject *res; double val; if (op == NULL) { PyErr_BadArgument(); return -1; } if (PyFloat_Check(op)) { return PyFloat_AS_DOUBLE(op); } nb = Py_TYPE(op)->tp_as_number; if (nb == NULL || nb->nb_float == NULL) { if (nb && nb->nb_index) { PyObject *res = _PyNumber_Index(op); if (!res) { return -1; } double val = PyLong_AsDouble(res); Py_DECREF(res); return val; } PyErr_Format(PyExc_TypeError, "must be real number, not %.50s", Py_TYPE(op)->tp_name); return -1; } res = (*nb->nb_float) (op); if (res == NULL) { return -1; } if (!PyFloat_CheckExact(res)) { if (!PyFloat_Check(res)) { PyErr_Format(PyExc_TypeError, "%T.__float__() must return a float, not %T", op, res); Py_DECREF(res); return -1; } if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, "%T.__float__() must return a float, not %T. " "The ability to return an instance of a strict subclass of float " "is deprecated, and may be removed in a future version of Python.", op, res)) { Py_DECREF(res); return -1; } } val = PyFloat_AS_DOUBLE(res); Py_DECREF(res); return val; } /* Macro and helper that convert PyObject obj to a C double and store the value in dbl. If conversion to double raises an exception, obj is set to NULL, and the function invoking this macro returns NULL. If obj is not of float or int type, Py_NotImplemented is incref'ed, stored in obj, and returned from the function invoking this macro. */ #define CONVERT_TO_DOUBLE(obj, dbl) \ if (PyFloat_Check(obj)) \ dbl = PyFloat_AS_DOUBLE(obj); \ else if (_Py_convert_int_to_double(&(obj), &(dbl)) < 0) \ return obj; /* Methods */ int _Py_convert_int_to_double(PyObject **v, double *dbl) { PyObject *obj = *v; if (PyLong_Check(obj)) { *dbl = PyLong_AsDouble(obj); if (*dbl == -1.0 && PyErr_Occurred()) { *v = NULL; return -1; } } else { *v = Py_NewRef(Py_NotImplemented); return -1; } return 0; } static PyObject * float_repr(PyObject *op) { PyFloatObject *v = _PyFloat_CAST(op); PyObject *result; char *buf; buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v), 'r', 0, Py_DTSF_ADD_DOT_0, NULL); if (!buf) return PyErr_NoMemory(); result = _PyUnicode_FromASCII(buf, strlen(buf)); PyMem_Free(buf); return result; } /* Comparison is pretty much a nightmare. When comparing float to float, * we do it as straightforwardly (and long-windedly) as conceivable, so * that, e.g., Python x == y delivers the same result as the platform * C x == y when x and/or y is a NaN. * When mixing float with an integer type, there's no good *uniform* approach. * Converting the double to an integer obviously doesn't work, since we * may lose info from fractional bits. Converting the integer to a double * also has two failure modes: (1) an int may trigger overflow (too * large to fit in the dynamic range of a C double); (2) even a C long may have * more bits than fit in a C double (e.g., on a 64-bit box long may have * 63 bits of precision, but a C double probably has only 53), and then * we can falsely claim equality when low-order integer bits are lost by * coercion to double. So this part is painful too. */ static PyObject* float_richcompare(PyObject *v, PyObject *w, int op) { double i, j; int r = 0; assert(PyFloat_Check(v)); i = PyFloat_AS_DOUBLE(v); /* Switch on the type of w. Set i and j to doubles to be compared, * and op to the richcomp to use. */ if (PyFloat_Check(w)) j = PyFloat_AS_DOUBLE(w); else if (!isfinite(i)) { if (PyLong_Check(w)) /* If i is an infinity, its magnitude exceeds any * finite integer, so it doesn't matter which int we * compare i with. If i is a NaN, similarly. */ j = 0.0; else goto Unimplemented; } else if (PyLong_Check(w)) { int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1; int wsign; int exponent; (void)PyLong_GetSign(w, &wsign); if (vsign != wsign) { /* Magnitudes are irrelevant -- the signs alone * determine the outcome. */ i = (double)vsign; j = (double)wsign; goto Compare; } /* The signs are the same. */ /* Convert w to a double if it fits. In particular, 0 fits. */ int64_t nbits64 = _PyLong_NumBits(w); assert(nbits64 >= 0); assert(!PyErr_Occurred()); if (nbits64 > DBL_MAX_EXP) { /* This Python integer is larger than any finite C double. * Replace with little doubles * that give the same outcome -- w is so large that * its magnitude must exceed the magnitude of any * finite float. */ i = (double)vsign; assert(wsign != 0); j = wsign * 2.0; goto Compare; } int nbits = (int)nbits64; if (nbits <= 48) { j = PyLong_AsDouble(w); /* It's impossible that <= 48 bits overflowed. */ assert(j != -1.0 || ! PyErr_Occurred()); goto Compare; } assert(wsign != 0); /* else nbits was 0 */ assert(vsign != 0); /* if vsign were 0, then since wsign is * not 0, we would have taken the * vsign != wsign branch at the start */ (void) frexp(i, &exponent); /* exponent is the # of bits in v before the radix point; * we know that nbits (the # of bits in w) > 48 at this point */ if (exponent < nbits) { j = i; i = 0.0; goto Compare; } if (exponent > nbits) { j = 0.0; goto Compare; } /* v and w have the same number of bits before the radix * point. Construct an int from the integer part of v and * update op if necessary, so comparing two ints has the same outcome. */ { double fracpart; double intpart; PyObject *result = NULL; PyObject *vv = NULL; fracpart = modf(i, &intpart); if (fracpart != 0.0) { switch (op) { /* Non-integer float never equals to an int. */ case Py_EQ: Py_RETURN_FALSE; case Py_NE: Py_RETURN_TRUE; /* For non-integer float, v <= w <=> v < w. * If v > 0: trunc(v) < v < trunc(v) + 1 * v < w => trunc(v) < w * trunc(v) < w => trunc(v) + 1 <= w => v < w * If v < 0: trunc(v) - 1 < v < trunc(v) * v < w => trunc(v) - 1 < w => trunc(v) <= w * trunc(v) <= w => v < w */ case Py_LT: case Py_LE: op = vsign > 0 ? Py_LT : Py_LE; break; /* The same as above, but with opposite directions. */ case Py_GT: case Py_GE: op = vsign > 0 ? Py_GE : Py_GT; break; } } vv = PyLong_FromDouble(intpart); if (vv == NULL) goto Error; r = PyObject_RichCompareBool(vv, w, op); if (r < 0) goto Error; result = PyBool_FromLong(r); Error: Py_XDECREF(vv); return result; } } /* else if (PyLong_Check(w)) */ else /* w isn't float or int */ goto Unimplemented; Compare: switch (op) { case Py_EQ: r = i == j; break; case Py_NE: r = i != j; break; case Py_LE: r = i <= j; break; case Py_GE: r = i >= j; break; case Py_LT: r = i < j; break; case Py_GT: r = i > j; break; } return PyBool_FromLong(r); Unimplemented: Py_RETURN_NOTIMPLEMENTED; } static Py_hash_t float_hash(PyObject *op) { PyFloatObject *v = _PyFloat_CAST(op); return _Py_HashDouble(op, v->ob_fval); } static PyObject * float_add(PyObject *v, PyObject *w) { double a,b; CONVERT_TO_DOUBLE(v, a); CONVERT_TO_DOUBLE(w, b); a = a + b; return PyFloat_FromDouble(a); } static PyObject * float_sub(PyObject *v, PyObject *w) { double a,b; CONVERT_TO_DOUBLE(v, a); CONVERT_TO_DOUBLE(w, b); a = a - b; return PyFloat_FromDouble(a); } static PyObject * float_mul(PyObject *v, PyObject *w) { double a,b; CONVERT_TO_DOUBLE(v, a); CONVERT_TO_DOUBLE(w, b); a = a * b; return PyFloat_FromDouble(a); } static PyObject * float_div(PyObject *v, PyObject *w) { double a,b; CONVERT_TO_DOUBLE(v, a); CONVERT_TO_DOUBLE(w, b); if (b == 0.0) { PyErr_SetString(PyExc_ZeroDivisionError, "division by zero"); return NULL; } a = a / b; return PyFloat_FromDouble(a); } static PyObject * float_rem(PyObject *v, PyObject *w) { double vx, wx; double mod; CONVERT_TO_DOUBLE(v, vx); CONVERT_TO_DOUBLE(w, wx); if (wx == 0.0) { PyErr_SetString(PyExc_ZeroDivisionError, "division by zero"); return NULL; } mod = fmod(vx, wx); if (mod) { /* ensure the remainder has the same sign as the denominator */ if ((wx < 0) != (mod < 0)) { mod += wx; } } else { /* the remainder is zero, and in the presence of signed zeroes fmod returns different results across platforms; ensure it has the same sign as the denominator. */ mod = copysign(0.0, wx); } return PyFloat_FromDouble(mod); } static void _float_div_mod(double vx, double wx, double *floordiv, double *mod) { double div; *mod = fmod(vx, wx); /* fmod is typically exact, so vx-mod is *mathematically* an exact multiple of wx. But this is fp arithmetic, and fp vx - mod is an approximation; the result is that div may not be an exact integral value after the division, although it will always be very close to one. */ div = (vx - *mod) / wx; if (*mod) { /* ensure the remainder has the same sign as the denominator */ if ((wx < 0) != (*mod < 0)) { *mod += wx; div -= 1.0; } } else { /* the remainder is zero, and in the presence of signed zeroes fmod returns different results across platforms; ensure it has the same sign as the denominator. */ *mod = copysign(0.0, wx); } /* snap quotient to nearest integral value */ if (div) { *floordiv = floor(div); if (div - *floordiv > 0.5) { *floordiv += 1.0; } } else { /* div is zero - get the same sign as the true quotient */ *floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */ } } static PyObject * float_divmod(PyObject *v, PyObject *w) { double vx, wx; double mod, floordiv; CONVERT_TO_DOUBLE(v, vx); CONVERT_TO_DOUBLE(w, wx); if (wx == 0.0) { PyErr_SetString(PyExc_ZeroDivisionError, "division by zero"); return NULL; } _float_div_mod(vx, wx, &floordiv, &mod); return Py_BuildValue("(dd)", floordiv, mod); } static PyObject * float_floor_div(PyObject *v, PyObject *w) { double vx, wx; double mod, floordiv; CONVERT_TO_DOUBLE(v, vx); CONVERT_TO_DOUBLE(w, wx); if (wx == 0.0) { PyErr_SetString(PyExc_ZeroDivisionError, "division by zero"); return NULL; } _float_div_mod(vx, wx, &floordiv, &mod); return PyFloat_FromDouble(floordiv); } /* determine whether x is an odd integer or not; assumes that x is not an infinity or nan. */ #define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0) static PyObject * float_pow(PyObject *v, PyObject *w, PyObject *z) { double iv, iw, ix; int negate_result = 0; if ((PyObject *)z != Py_None) { PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not " "allowed unless all arguments are integers"); return NULL; } CONVERT_TO_DOUBLE(v, iv); CONVERT_TO_DOUBLE(w, iw); /* Sort out special cases here instead of relying on pow() */ if (iw == 0) { /* v**0 is 1, even 0**0 */ return PyFloat_FromDouble(1.0); } if (isnan(iv)) { /* nan**w = nan, unless w == 0 */ return PyFloat_FromDouble(iv); } if (isnan(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */ return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw); } if (isinf(iw)) { /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if * abs(v) > 1 (including case where v infinite) * * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if * abs(v) > 1 (including case where v infinite) */ iv = fabs(iv); if (iv == 1.0) return PyFloat_FromDouble(1.0); else if ((iw > 0.0) == (iv > 1.0)) return PyFloat_FromDouble(fabs(iw)); /* return inf */ else return PyFloat_FromDouble(0.0); } if (isinf(iv)) { /* (+-inf)**w is: inf for w positive, 0 for w negative; in * both cases, we need to add the appropriate sign if w is * an odd integer. */ int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw); if (iw > 0.0) return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv)); else return PyFloat_FromDouble(iw_is_odd ? copysign(0.0, iv) : 0.0); } if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero (already dealt with above), and an error if w is negative. */ int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw); if (iw < 0.0) { PyErr_SetString(PyExc_ZeroDivisionError, "zero to a negative power"); return NULL; } /* use correct sign if iw is odd */ return PyFloat_FromDouble(iw_is_odd ? iv : 0.0); } if (iv < 0.0) { /* Whether this is an error is a mess, and bumps into libm * bugs so we have to figure it out ourselves. */ if (iw != floor(iw)) { /* Negative numbers raised to fractional powers * become complex. */ return PyComplex_Type.tp_as_number->nb_power(v, w, z); } /* iw is an exact integer, albeit perhaps a very large * one. Replace iv by its absolute value and remember * to negate the pow result if iw is odd. */ iv = -iv; negate_result = DOUBLE_IS_ODD_INTEGER(iw); } if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */ /* (-1) ** large_integer also ends up here. Here's an * extract from the comments for the previous * implementation explaining why this special case is * necessary: * * -1 raised to an exact integer should never be exceptional. * Alas, some libms (chiefly glibc as of early 2003) return * NaN and set EDOM on pow(-1, large_int) if the int doesn't * happen to be representable in a *C* integer. That's a * bug. */ return PyFloat_FromDouble(negate_result ? -1.0 : 1.0); } /* Now iv and iw are finite, iw is nonzero, and iv is * positive and not equal to 1.0. We finally allow * the platform pow to step in and do the rest. */ errno = 0; ix = pow(iv, iw); _Py_ADJUST_ERANGE1(ix); if (negate_result) ix = -ix; if (errno != 0) { /* We don't expect any errno value other than ERANGE, but * the range of libm bugs appears unbounded. */ PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError : PyExc_ValueError); return NULL; } return PyFloat_FromDouble(ix); } #undef DOUBLE_IS_ODD_INTEGER static PyObject * float_neg(PyObject *op) { PyFloatObject *v = _PyFloat_CAST(op); return PyFloat_FromDouble(-v->ob_fval); } static PyObject * float_abs(PyObject *op) { PyFloatObject *v = _PyFloat_CAST(op); return PyFloat_FromDouble(fabs(v->ob_fval)); } static int float_bool(PyObject *op) { PyFloatObject *v = _PyFloat_CAST(op); return v->ob_fval != 0.0; } /*[clinic input] float.is_integer Return True if the float is an integer. [clinic start generated code]*/ static PyObject * float_is_integer_impl(PyObject *self) /*[clinic end generated code: output=7112acf95a4d31ea input=311810d3f777e10d]*/ { double x = PyFloat_AsDouble(self); PyObject *o; if (x == -1.0 && PyErr_Occurred()) return NULL; if (!isfinite(x)) Py_RETURN_FALSE; errno = 0; o = (floor(x) == x) ? Py_True : Py_False; if (errno != 0) { PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError : PyExc_ValueError); return NULL; } return Py_NewRef(o); } /*[clinic input] float.__trunc__ Return the Integral closest to x between 0 and x. [clinic start generated code]*/ static PyObject * float___trunc___impl(PyObject *self) /*[clinic end generated code: output=dd3e289dd4c6b538 input=591b9ba0d650fdff]*/ { return PyLong_FromDouble(PyFloat_AS_DOUBLE(self)); } /*[clinic input] float.__floor__ Return the floor as an Integral. [clinic start generated code]*/ static PyObject * float___floor___impl(PyObject *self) /*[clinic end generated code: output=e0551dbaea8c01d1 input=77bb13eb12e268df]*/ { double x = PyFloat_AS_DOUBLE(self); return PyLong_FromDouble(floor(x)); } /*[clinic input] float.__ceil__ Return the ceiling as an Integral. [clinic start generated code]*/ static PyObject * float___ceil___impl(PyObject *self) /*[clinic end generated code: output=a2fd8858f73736f9 input=79e41ae94aa0a516]*/ { double x = PyFloat_AS_DOUBLE(self); return PyLong_FromDouble(ceil(x)); } /* double_round: rounds a finite double to the closest multiple of 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <= ndigits <= 323). Returns a Python float, or sets a Python error and returns NULL on failure (OverflowError and memory errors are possible). */ #if _PY_SHORT_FLOAT_REPR == 1 /* version of double_round that uses the correctly-rounded string<->double conversions from Python/dtoa.c */ static PyObject * double_round(double x, int ndigits) { double rounded; Py_ssize_t buflen, mybuflen=100; char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf; int decpt, sign; PyObject *result = NULL; _Py_SET_53BIT_PRECISION_HEADER; /* round to a decimal string */ _Py_SET_53BIT_PRECISION_START; buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end); _Py_SET_53BIT_PRECISION_END; if (buf == NULL) { PyErr_NoMemory(); return NULL; } /* Get new buffer if shortbuf is too small. Space needed <= buf_end - buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */ buflen = buf_end - buf; if (buflen + 8 > mybuflen) { mybuflen = buflen+8; mybuf = (char *)PyMem_Malloc(mybuflen); if (mybuf == NULL) { PyErr_NoMemory(); goto exit; } } /* copy buf to mybuf, adding exponent, sign and leading 0 */ PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""), buf, decpt - (int)buflen); /* and convert the resulting string back to a double */ errno = 0; _Py_SET_53BIT_PRECISION_START; rounded = _Py_dg_strtod(mybuf, NULL); _Py_SET_53BIT_PRECISION_END; if (errno == ENOMEM) { PyErr_NoMemory(); } else if (errno == ERANGE && fabs(rounded) >= 1.) { PyErr_SetString(PyExc_OverflowError, "rounded value too large to represent"); } else { result = PyFloat_FromDouble(rounded); } /* done computing value; now clean up */ if (mybuf != shortbuf) PyMem_Free(mybuf); exit: _Py_dg_freedtoa(buf); return result; } #else // _PY_SHORT_FLOAT_REPR == 0 /* fallback version, to be used when correctly rounded binary<->decimal conversions aren't available */ static PyObject * double_round(double x, int ndigits) { double pow1, pow2, y, z; if (ndigits >= 0) { if (ndigits > 22) { /* pow1 and pow2 are each safe from overflow, but pow1*pow2 ~= pow(10.0, ndigits) might overflow */ pow1 = pow(10.0, (double)(ndigits-22)); pow2 = 1e22; } else { pow1 = pow(10.0, (double)ndigits); pow2 = 1.0; } y = (x*pow1)*pow2; /* if y overflows, then rounded value is exactly x */ if (!isfinite(y)) return PyFloat_FromDouble(x); } else { pow1 = pow(10.0, (double)-ndigits); pow2 = 1.0; /* unused; silences a gcc compiler warning */ y = x / pow1; } z = round(y); if (fabs(y-z) == 0.5) /* halfway between two integers; use round-half-even */ z = 2.0*round(y/2.0); if (ndigits >= 0) z = (z / pow2) / pow1; |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |