Source

bigfloat / bigfloat_cython / bigfloat / core.py

Full commit
   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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
# -*- coding: UTF-8

# Copyright 2009--2011 Mark Dickinson.
#
# This file is part of the bigfloat package.
#
# The bigfloat package is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# The bigfloat package is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
# for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with the bigfloat package.  If not, see <http://www.gnu.org/licenses/>.

# Python wrapper for MPFR library


import sys as _sys
import contextlib as _contextlib

import bigfloat.mpfr as mpfr

from bigfloat.rounding_mode import (
    ROUND_TIES_TO_EVEN,
    ROUND_TOWARD_ZERO,
    ROUND_TOWARD_POSITIVE,
    ROUND_TOWARD_NEGATIVE,
)

from bigfloat.context import (
    Context,
    DefaultContext,
    EmptyContext,

    RoundTowardPositive,
    RoundTowardNegative,

    _apply_function_in_current_context,
    precision,
)


# Alternative names for some builtins that get overwritten by functions created
# in this module.
_builtin_max = max
_builtin_min = min
_builtin_abs = abs
_builtin_pow = pow


_PyHASH_MODULUS = _sys.hash_info.modulus
_PyHASH_INF = _sys.hash_info.inf
_PyHASH_NAN = _sys.hash_info.nan

# _PyHASH_2INV is the inverse of 2 modulo the prime _PyHASH_MODULUS
_PyHASH_2INV = _builtin_pow(2, _PyHASH_MODULUS - 2, _PyHASH_MODULUS)


def _mpfr_get_str2(base, ndigits, op, rounding_mode):
    """
    Variant of mpfr_get_str, for internal use:  simply splits off the '-'
    sign from the digit string, and returns a triple

        (sign, digits, exp)

    Also converts the byte-string produced by mpfr_get_str to Unicode.

    """
    digits, exp = mpfr.mpfr_get_str(base, ndigits, op, rounding_mode)
    digits = digits.decode('ascii')
    negative = digits.startswith('-')
    if negative:
        digits = digits[1:]
    return negative, digits, exp


###############################################################################
# Context manager to give an easy way to change emin and emax temporarily.

try:
    DBL_PRECISION = _sys.float_info.mant_dig
except AttributeError:
    # Python 2.5 and earlier don't have sys.float_info; it's enough for
    # DBL_PRECISION to be an upper bound.  64 bits should always be enough.
    DBL_PRECISION = 64

# Dealing with exponent limits
# ----------------------------
# The MPFR documentation for mpfr_set_emin and mpfr_set_emax says:
#
#   "If the user changes the exponent range, it is her/his
#   responsibility to check that all current floating-point variables
#   are in the new allowed range (for example using mpfr_check_range),
#   otherwise the subsequent behavior will be undefined, in the sense
#   of the ISO C standard."
#
# Some MPFR operations and functions (including at least mpfr_add and
# mpfr_nexttoward) appear to assume that input arguments have
# exponents within the current [emin, emax] range.
#
# This assumption is inconsistent with the way that we'd like the
# bigfloat package to operate: a standard operation on BigFloats
# shouldn't care if the inputs to the operation are outside the
# current context; it should only worry about forcing the output into
# the format specified by the current context.  So we adopt the
# following approach:
#
# We define constants EMAX_MAX and EMIN_MIN representing the min and
# max values we'll allow for both emin and emax (these aren't
# necessarily the same as the values returned by mpfr_emin_min and
# mpfr_emax_max).  When the module is imported, emax and emin are
# set to these values.
#
# After this, the MPFR stored emax and emin aren't touched when the
# context is changed; but for each standard operation or function, the
# function is performed with emax=EMAX_MAX and emin=EMIN_MIN.  *Then*
# the exponents are changed, mpfr_check_range is called (also
# mpfr_subnormalize if necessary), and the exponents stored by MPFR
# are restored to their original state.
#
# Any BigFloat instance that's created *must* have exponent in the
# range [EMIN_MIN, EMAX_MAX] (unless it's a zero, infinity or nan).

EMAX_MAX = mpfr.MPFR_EMAX_DEFAULT
EMIN_MIN = mpfr.MPFR_EMIN_DEFAULT

EMAX_MIN = _builtin_max(mpfr.MPFR_EMIN_DEFAULT, mpfr.mpfr_get_emax_min())
EMIN_MAX = _builtin_min(mpfr.MPFR_EMAX_DEFAULT, mpfr.mpfr_get_emin_max())

mpfr.mpfr_set_emin(EMIN_MIN)
mpfr.mpfr_set_emax(EMAX_MAX)

PRECISION_MIN = mpfr.MPFR_PREC_MIN
PRECISION_MAX = mpfr.MPFR_PREC_MAX

_bit_length_correction = {
    '0': 4, '1': 3, '2': 2, '3': 2, '4': 1, '5': 1, '6': 1, '7': 1,
    '8': 0, '9': 0, 'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0, 'f': 0,
    }


def _bit_length(n):
    """Bit length of an integer"""
    hex_n = '%x' % _builtin_abs(n)
    return 4 * len(hex_n) - _bit_length_correction[hex_n[0]]


def _format_finite(negative, digits, dot_pos):
    """Given a (possibly empty) string of digits and an integer
    dot_pos indicating the position of the decimal point relative to
    the start of that string, output a formatted numeric string with
    the same value and same implicit exponent."""

    # strip leading zeros
    olddigits = digits
    digits = digits.lstrip('0')
    dot_pos -= len(olddigits) - len(digits)

    # value is 0.digits * 10**dot_pos
    use_exponent = dot_pos <= -4 or dot_pos > len(digits)
    if use_exponent:
        exp = dot_pos - 1 if digits else dot_pos
        dot_pos -= exp

    # left pad with zeros, insert decimal point, and add exponent
    if dot_pos <= 0:
        digits = '0' * (1 - dot_pos) + digits
        dot_pos += 1 - dot_pos
    assert 1 <= dot_pos <= len(digits)
    if dot_pos < len(digits):
        digits = digits[:dot_pos] + '.' + digits[dot_pos:]
    if use_exponent:
        digits += "e%+d" % exp
    return '-' + digits if negative else digits


def next_up(x, context=None):
    """next_up(x): return the least representable float that's
    strictly greater than x.

    This operation is quiet:  flags are not affected.

    """
    x = BigFloat._implicit_convert(x)
    # make sure we don't alter any flags
    with _saved_flags():
        with (context if context is not None else EmptyContext):
            with RoundTowardPositive:
                # nan maps to itself
                if is_nan(x):
                    return +x

                # round to current context; if value changes, we're done
                y = +x
                if y != x:
                    return y

                # otherwise apply mpfr_nextabove
                bf = y.copy()
                mpfr.mpfr_nextabove(bf)
                # apply + one more time to deal with subnormals
                return +bf


def next_down(x, context=None):
    """next_down(x): return the greatest representable float that's
    strictly less than x.

    This operation is quiet:  flags are not affected.

    """
    x = BigFloat._implicit_convert(x)
    # make sure we don't alter any flags
    with _saved_flags():
        with (context if context is not None else EmptyContext):
            with RoundTowardNegative:
                # nan maps to itself
                if is_nan(x):
                    return +x

                # round to current context; if value changes, we're done
                y = +x
                if y != x:
                    return y

                # otherwise apply mpfr_nextabove
                bf = y.copy()
                mpfr.mpfr_nextbelow(bf)
                # apply + one more time to deal with subnormals
                return +bf


def _binop(op):
    def wrapped_op(self, other):
        try:
            result = op(self, other)
        except TypeError:
            result = NotImplemented
        return result
    return wrapped_op


def _rbinop(op):
    def wrapped_op(self, other):
        try:
            result = op(other, self)
        except TypeError:
            result = NotImplemented
        return result
    return wrapped_op


class BigFloat(mpfr.Mpfr_t):
    def __new__(cls, value, context=None):
        """Create BigFloat from integer, float, string or another BigFloat.

        If the context keyword argument is not given, the result
        format and the rounding mode

        Uses the current precision and rounding mode, unless an
        alternative context is given.

        """
        if context is not None:
            with context:
                return cls(value)

        if isinstance(value, float):
            return _set_d(value)
        elif isinstance(value, str):
            return set_str2(value.strip(), 10)
        elif isinstance(value, int):
            return set_str2('%x' % value, 16)
        elif isinstance(value, BigFloat):
            return pos(value)
        else:
            raise TypeError("Can't convert argument %s of type %s "
                            "to BigFloat" % (value, type(value)))

    @classmethod
    def fromhex(cls, value, context=None):
        with (context if context is not None else EmptyContext):
            return set_str2(value, 16)

    # alternative constructor, that does exact conversions
    @classmethod
    def exact(cls, value, precision=None):
        """Convert an integer, float or BigFloat with no loss of precision.
        Also convert a string with given precision.

        This constructor makes no use of the current context.
        """

        # figure out precision to use
        if isinstance(value, str):
            if precision is None:
                raise TypeError("precision must be supplied when "
                                "converting from a string")
        else:
            if precision is not None:
                raise TypeError("precision argument should not be "
                                "specified except when converting "
                                "from a string")
            if isinstance(value, float):
                precision = _builtin_max(DBL_PRECISION, PRECISION_MIN)
            elif isinstance(value, int):
                precision = _builtin_max(_bit_length(value), PRECISION_MIN)
            elif isinstance(value, BigFloat):
                precision = value.precision
            else:
                raise TypeError("Can't convert argument %s of type %s "
                                "to BigFloat" % (value, type(value)))

        # use Default context, with given precision
        with _saved_flags():
            set_flagstate(set())  # clear all flags
            with DefaultContext + Context(precision=precision):
                result = BigFloat(value)
            if test_flag(Overflow):
                raise ValueError("value too large to represent as a BigFloat")
            if test_flag(Underflow):
                raise ValueError("value too small to represent as a BigFloat")
            if test_flag(Inexact) and not isinstance(value, str):
                # since this is supposed to be an exact conversion, the
                # inexact flag should never be set except when converting
                # from a string.
                assert False, ("Inexact conversion in BigFloat.exact. "
                               "This shouldn't ever happen.  Please report.")

        return result

    def __int__(self):
        """BigFloat -> int.

        Rounds using RoundTowardZero, regardless of current rounding mode.

        """
        # convert via hex string; rounding mode doesn't matter here,
        # since conversion should be exact
        if not is_finite(self):
            raise ValueError("Can't convert infinity or nan to integer")

        # Conversion to base 16 is exact, so any rounding mode will do.
        negative, digits, e = _mpfr_get_str2(
            16,
            0,
            self,
            ROUND_TIES_TO_EVEN,
        )
        n = int(digits, 16)
        e = 4 * (e - len(digits))
        if e >= 0:
            n <<= e
        else:
            n >>= -e
        return int(-n) if negative else int(n)

    def __float__(self):
        """BigFloat -> float.

        Rounds using RoundTiesToEven, regardless of current rounding mode.

        """
        return mpfr.mpfr_get_d(self, ROUND_TIES_TO_EVEN)

    def _sign(self):
        return mpfr.mpfr_signbit(self)

    def _significand(self):
        """Return the significand of self, as a BigFloat.

        If self is a nonzero finite number, return a BigFloat m
        with the same precision as self, such that

          0.5 <= m < 1. and
          self = +/-m * 2**e

        for some exponent e.

        If self is zero, infinity or nan, return a copy of self with
        the sign set to 0.

        """
        m = self.copy()
        if self and is_finite(self):
            mpfr.mpfr_set_exp(m, 0)
        mpfr.mpfr_setsign(m, m, False, ROUND_TIES_TO_EVEN)
        return m

    def _exponent(self):
        """Return the exponent of self, as an integer.

        The exponent is defined as the unique integer k such that
        2**(k-1) <= abs(self) < 2**k.

        If self is not finite and nonzero, return a string:  one
        of '0', 'Infinity' or 'NaN'.

        """

        if self and is_finite(self):
            return mpfr.mpfr_get_exp(self)

        if not self:
            return '0'
        elif is_inf(self):
            return 'Infinity'
        elif is_nan(self):
            return 'NaN'
        else:
            assert False, "shouldn't ever get here"

    def copy(self):
        """ Return a copy of self.

        This function does not make use of the context.  The result has the
        same precision as the original.

        """
        result = mpfr.Mpfr_t.__new__(BigFloat)
        mpfr.mpfr_init2(result, self.precision)
        mpfr.mpfr_set(result, self, ROUND_TIES_TO_EVEN)
        return result

    def copy_neg(self):
        """ Return a copy of self with the opposite sign bit.

        Unlike -self, this does not make use of the context:  the result
        has the same precision as the original.

        """
        result = mpfr.Mpfr_t.__new__(BigFloat)
        mpfr.mpfr_init2(result, self.precision)
        new_sign = not self._sign()
        mpfr.mpfr_setsign(result, self, new_sign, ROUND_TIES_TO_EVEN)
        return result

    def copy_abs(self):
        """ Return a copy of self with the sign bit unset.

        Unlike abs(self), this does not make use of the context: the result
        has the same precision as the original.

        """
        result = mpfr.Mpfr_t.__new__(BigFloat)
        mpfr.mpfr_init2(result, self.precision)
        mpfr.mpfr_setsign(result, self, False, ROUND_TIES_TO_EVEN)
        return result

    def hex(self):
        """Return a hexadecimal representation of a BigFloat."""

        sign = '-' if self._sign() else ''
        e = self._exponent()
        if isinstance(e, str):
            return sign + e

        m = self._significand()
        _, digits, _ = _mpfr_get_str2(
            16,
            0,
            m,
            ROUND_TIES_TO_EVEN,
        )
        # only print the number of digits that are actually necessary
        n = 1 + (self.precision - 1) // 4
        assert all(c == '0' for c in digits[n:])
        result = '%s0x0.%sp%+d' % (sign, digits[:n], e)
        return result

    def as_integer_ratio(self):
        """Return pair n, d of integers such that the value of self is
        exactly equal to n/d, n and d are relatively prime, and d >= 1.

        """
        if not is_finite(self):
            raise ValueError("Can't express infinity or nan as "
                             "an integer ratio")
        elif not self:
            return 0, 1

        # convert to a hex string, and from there to a fraction
        negative, digits, e = _mpfr_get_str2(
            16,
            0,
            self,
            ROUND_TIES_TO_EVEN,
        )
        digits = digits.rstrip('0')

        # find number of trailing 0 bits in last hex digit
        v = int(digits[-1], 16)
        v &= -v
        n, d = int(digits, 16) // v, 1
        e = (e - len(digits) << 2) + {1: 0, 2: 1, 4: 2, 8: 3}[v]

        # abs(number) now has value n * 2**e, and n is odd
        if e >= 0:
            n <<= e
        else:
            d <<= -e

        return (-n if negative else n), d

    def __str__(self):
        if is_zero(self):
            return '-0' if is_negative(self) else '0'
        elif is_finite(self):
            negative, digits, e = _mpfr_get_str2(
                10,
                0,
                self,
                ROUND_TIES_TO_EVEN,
            )
            return _format_finite(negative, digits, e)
        elif is_inf(self):
            return '-Infinity' if is_negative(self) else 'Infinity'
        else:
            assert is_nan(self)
            return 'NaN'

    def __repr__(self):
        return "BigFloat.exact('%s', precision=%d)" % (
            str(self), self.precision)

    def _format_to_precision_one(self):
        """ Format 'self' to one significant figure.

        This is a special case of _format_to_floating_precision, made necessary
        because the mpfr_get_str function doesn't support passing a precision
        smaller than 2 (according to the docs), so we need some trickery to
        make this work.

        Rounding is always round-to-nearest.
        """

        # Start by formatting to 2 digits; we'll then truncate to one digit,
        # rounding appropriately.
        sign, digits, exp = _mpfr_get_str2(
            10,
            2,
            self,
            ROUND_TOWARD_NEGATIVE,
        )

        # If the last digit is 5, we can't tell which way to round; instead,
        # recompute with the opposite rounding direction, and round based on
        # the result of that.
        if digits[-1] == '5':
            sign, digits, exp = _mpfr_get_str2(
                10,
                2,
                self,
                ROUND_TOWARD_POSITIVE,
            )

        if digits[-1] in '01234':
            round_up = False
        elif digits[-1] in '6789':
            round_up = True
        else:
            # Halfway case: round to even.
            round_up = digits[-2] in '13579'

        digits = digits[:-1]
        if round_up:
            digits = str(int(digits) + 1)
            if len(digits) == 2:
                assert digits[-1] == '0'
                digits = digits[:-1]
                exp += 1
        return sign, digits, exp - 1

    def _format_to_floating_precision(self, precision):
        """ Format a nonzero finite BigFloat instance to a given number of
        significant digits.

        Returns a triple (negative, digits, exp) where:

          - negative is a boolean, True for a negative number, else False
          - digits is a string giving the digits of the output
          - exp represents the exponent of the output,

        The normalization of the exponent is such that <digits>E<exp>
        represents the decimal approximation to self.

        Rounding is always round-to-nearest.
        """
        if precision <= 0:
            raise ValueError("precision argument should be at least 1")

        if precision == 1:
            return self._format_to_precision_one()

        sign, digits, exp = _mpfr_get_str2(
            10,
            precision,
            self,
            ROUND_TIES_TO_EVEN,
        )

        return sign, digits, exp - len(digits)

    def _format_to_fixed_precision(self, precision):
        """ Format 'self' to a given number of digits after the decimal point.

        Returns a triple (negative, digits, exp) where:

          - negative is a boolean, True for a negative number, else False
          - digits is a string giving the digits of the output
          - exp represents the exponent of the output

        The normalization of the exponent is such that <digits>E<exp>
        represents the decimal approximation to self.

        """
        # MPFR only provides functions to format to a given number of
        # significant digits.  So we must:
        #
        #   (1) Identify an e such that 10**(e-1) <= abs(x) < 10**e.
        #
        #   (2) Determine the number of significant digits required, and format
        #       to that number of significant digits.
        #
        #   (3) Adjust output if necessary if it's been rounded up to 10**e.

        # Zeros
        if is_zero(self):
            return is_negative(self), '0', -precision

        # Specials
        if is_inf(self):
            return is_negative(self), 'Infinity', None

        if is_nan(self):
            return is_negative(self), 'NaN', None

        # Figure out the exponent by making a call to get_str2.  exp satisfies
        # 10**(exp-1) <= self < 10**exp
        _, _, exp = _mpfr_get_str2(
            10,
            2,
            self,
            ROUND_TOWARD_ZERO,
        )

        sig_figs = exp + precision

        if sig_figs < 0:
            sign = self._sign()
            return sign, '0', -precision

        elif sig_figs == 0:
            # Ex: 0.1 <= x < 1.0, rounding x to nearest multiple of 1.0.
            # Or: 100.0 <= x < 1000.0, rounding x to nearest multiple of 1000.0
            sign, digits, new_exp = _mpfr_get_str2(
                10,
                2,
                self,
                ROUND_TOWARD_NEGATIVE,
            )
            if int(digits) == 50:
                # Halfway case
                sign, digits, new_exp = _mpfr_get_str2(
                    10,
                    2,
                    self,
                    ROUND_TOWARD_POSITIVE,
                )

            digits = '1' if int(digits) > 50 or new_exp == exp + 1 else '0'
            return sign, digits, -precision

        negative, digits, new_exp = self._format_to_floating_precision(
            sig_figs
        )

        # It's possible that the rounding up involved changes the exponent;
        # in that case we have to adjust the digits accordingly.  The only
        # possibility should be that new_exp == exp + 1.
        if new_exp + len(digits) != exp:
            assert new_exp + len(digits) == exp + 1
            digits += '0'

        return negative, digits, -precision

    def __hash__(self):
        if is_nan(self):
            return _PyHASH_NAN
        elif is_inf(self):
            return -_PyHASH_INF if is_negative(self) else _PyHASH_INF
        elif is_zero(self):
            return 0

        negative, digits, e = _mpfr_get_str2(
            16,
            0,
            self,
            ROUND_TIES_TO_EVEN,
        )
        # Find binary exponent.
        e = 4 * (e - len(digits))

        # The value of self is (-1)**negative * int(digits, 16) * 2**e.
        if e >= 0:
            exp_hash = _builtin_pow(2, e, _PyHASH_MODULUS)
        else:
            exp_hash = _builtin_pow(_PyHASH_2INV, -e, _PyHASH_MODULUS)
        hash_ = int(digits, 16) * exp_hash % _PyHASH_MODULUS
        ans = -hash_ if negative else hash_
        return -2 if ans == -1 else ans

    def __ne__(self, other):
        return not (self == other)

    def __bool__(self):
        return not is_zero(self)

    @property
    def precision(self):
        return mpfr.mpfr_get_prec(self)

    @classmethod
    def _implicit_convert(cls, arg):
        """Implicit conversion used for binary operations, comparisons,
        functions, etc.  Return value should be an instance of
        BigFloat."""

        # ints, long and floats mix freely with BigFloats, and are
        # converted exactly.
        if isinstance(arg, (int, float)):
            return cls.exact(arg)
        elif isinstance(arg, BigFloat):
            return arg
        else:
            raise TypeError("Unable to convert argument %s of type %s "
                            "to BigFloat" % (arg, type(arg)))

###############################################################################
# Flags
#
# MPFR has 5 flags available, one of which we shouldn't encounter in
# normal use.  We need functions to save and restore the current flag
# state.

Inexact = 'Inexact'
Overflow = 'Overflow'
Underflow = 'Underflow'
NanFlag = 'NanFlag'
ZeroDivision = 'ZeroDivision'

_all_flags = set([Inexact, Overflow, Underflow, NanFlag, ZeroDivision])

_flag_translate = {
    'underflow': Underflow,
    'overflow': Overflow,
    'nanflag': NanFlag,
    'inexflag': Inexact,
    'divby0': ZeroDivision,
}

_clear_flag_fns = dict((v, getattr(mpfr, 'mpfr_clear_' + k))
                      for k, v in _flag_translate.items())
_set_flag_fns = dict((v, getattr(mpfr, 'mpfr_set_' + k))
                    for k, v in _flag_translate.items())
_test_flag_fns = dict((v, getattr(mpfr, 'mpfr_' + k + '_p'))
                     for k, v in _flag_translate.items())


def test_flag(f):
    """
    Return True if the given flag is set, and False otherwise.

    """
    return _test_flag_fns[f]()


def set_flag(f):
    """
    Set the given flag.

    """
    return _set_flag_fns[f]()


def clear_flag(f):
    """
    Clear the given flag.

    """
    return _clear_flag_fns[f]()


def get_flagstate():
    """
    Return a set containing the flags that are currently set.

    """
    return set(f for f in _all_flags if test_flag(f))


def set_flagstate(flagset):
    """
    Set all flags in ``flagset``, and clear all other flags.

    """
    if not flagset <= _all_flags:
        raise ValueError("unrecognized flags in flagset")

    for f in flagset:
        set_flag(f)
    for f in _all_flags - flagset:
        clear_flag(f)


@_contextlib.contextmanager
def _saved_flags():
    """Save current flags for the duration of a with block.  Restore
    those original flags after the block completes."""

    old_flags = get_flagstate()
    try:
        yield
    finally:
        set_flagstate(old_flags)


def _set_d(x, context=None):
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_set_d,
        (x,),
        context,
    )


def _set_from_whole_string(rop, s, base, rnd):
    """
    Helper function for set_str2: accept a string, set rop, and return the
    appropriate ternary value.  Raise ValueError if ``s`` doesn't represent
    a valid string in the given base.

    """
    s = s.encode('ascii').strip()
    ternary, endindex = mpfr.mpfr_strtofr(rop, s, base, rnd)
    if len(s) != endindex:
        raise ValueError("not a valid numeric string")
    return ternary


def set_str2(s, base, context=None):
    """
    Convert the string ``s`` in base ``base`` to a BigFloat instance, rounding
    according to the current context.

    Raise ValueError if ``s`` doesn't represent a valid string in the given
    base.

    """
    return _apply_function_in_current_context(
        BigFloat,
        _set_from_whole_string,
        (s, base),
        context,
    )


###############################################################################
# 5.2 Assignment Functions
###############################################################################

def pos(x, context=None):
    """
    Return ``x``.

    As usual, the result is rounded to the current context.  The ``pos``
    function can be useful for rounding an intermediate result, computed with a
    temporary increase in precision, back to the current context.  For
    example::

        >>> pow(3, 20) + 1.234 - pow(3, 20)  # inaccurate due to precision loss
        BigFloat.exact('1.2340002059936523', precision=53)
        >>> with precision(100):  # compute result with extra precision
        ...     x = pow(3, 20) + 1.234 - pow(3, 20)
        ...
        >>> x
        BigFloat.exact('1.2339999999999999857891452847980', precision=100)
        >>> pos(x)  # round back to original precision
        BigFloat.exact('1.2340000000000000', precision=53)

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_set,
        (BigFloat._implicit_convert(x),),
        context,
    )


###############################################################################
# 5.5 Basic Arithmetic Functions
###############################################################################

def add(x, y, context=None):
    """
    Return ``x`` + ``y``.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_add,
        (
            BigFloat._implicit_convert(x),
            BigFloat._implicit_convert(y),
        ),
        context,
    )


def sub(x, y, context=None):
    """
    Return ``x`` - ``y``.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_sub,
        (
            BigFloat._implicit_convert(x),
            BigFloat._implicit_convert(y),
        ),
        context,
    )


def mul(x, y, context=None):
    """
    Return ``x`` times ``y``.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_mul,
        (
            BigFloat._implicit_convert(x),
            BigFloat._implicit_convert(y),
        ),
        context,
    )


def sqr(x, context=None):
    """
    Return the square of ``x``.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_sqr,
        (BigFloat._implicit_convert(x),),
        context,
    )


def div(x, y, context=None):
    """
    Return ``x`` divided by ``y``.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_div,
        (
            BigFloat._implicit_convert(x),
            BigFloat._implicit_convert(y),
        ),
        context,
    )


def sqrt(x, context=None):
    """
    Return the square root of ``x``.

    Return -0 if x is -0, to be consistent with the IEEE 754 standard.  Return
    NaN if x is negative.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_sqrt,
        (BigFloat._implicit_convert(x),),
        context,
    )


def rec_sqrt(x, context=None):
    """
    Return the reciprocal square root of x.

    Return +Inf if x is ±0, +0 if x is +Inf, and NaN if x is negative.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_rec_sqrt,
        (BigFloat._implicit_convert(x),),
        context,
    )


def cbrt(x, context=None):
    """
    Return the cube root of x.

    For x negative, return a negative number.  The cube root of -0 is defined
    to be -0.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_cbrt,
        (BigFloat._implicit_convert(x),),
        context,
    )


def root(x, k, context=None):
    """
    Return the kth root of x.

    For k odd and x negative (including -Inf), return a negative number.
    For k even and x negative (including -Inf), return NaN.

    The kth root of -0 is defined to be -0, whatever the parity of k.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_cbrt,
        (BigFloat._implicit_convert(x),),
        context,
    )


def pow(x, y, context=None):
    """
    Return ``x`` raised to the power ``y``.

    Special values are handled as described in the ISO C99 and IEEE 754-2008
    standards for the pow function.

      * pow(±0, y) returns plus or minus infinity for y a negative odd integer.

      * pow(±0, y) returns plus infinity for y negative and not an odd integer.

      * pow(±0, y) returns plus or minus zero for y a positive odd integer.

      * pow(±0, y) returns plus zero for y positive and not an odd integer.

      * pow(-1, ±Inf) returns 1.

      * pow(+1, y) returns 1 for any y, even a NaN.

      * pow(x, ±0) returns 1 for any x, even a NaN.

      * pow(x, y) returns NaN for finite negative x and finite non-integer y.

      * pow(x, -Inf) returns plus infinity for 0 < abs(x) < 1, and plus zero
        for abs(x) > 1.

      * pow(x, +Inf) returns plus zero for 0 < abs(x) < 1, and plus infinity
        for abs(x) > 1.

      * pow(-Inf, y) returns minus zero for y a negative odd integer.

      * pow(-Inf, y) returns plus zero for y negative and not an odd integer.

      * pow(-Inf, y) returns minus infinity for y a positive odd integer.

      * pow(-Inf, y) returns plus infinity for y positive and not an odd
        integer.

      * pow(+Inf, y) returns plus zero for y negative, and plus infinity for y
        positive.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_pow,
        (
            BigFloat._implicit_convert(x),
            BigFloat._implicit_convert(y),
        ),
        context,
    )


def neg(x, context=None):
    """
    Return -x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_neg,
        (BigFloat._implicit_convert(x),),
        context,
    )


def abs(x, context=None):
    """
    Return abs(x).

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_abs,
        (BigFloat._implicit_convert(x),),
        context,
    )


def dim(x, y, context=None):
    """
    Return max(x - y, 0).

    Return x - y if x > y, +0 if x <= y, and NaN if either x or y is NaN.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_dim,
        (
            BigFloat._implicit_convert(x),
            BigFloat._implicit_convert(y),
        ),
        context,
    )


###############################################################################
# 5.6 Comparison Functions
###############################################################################

def cmp(op1, op2):
    """
    Perform a three-way comparison of op1 and op2.

    Return a positive value if op1 > op2, zero if op1 = op2, and a negative
    value if op1 < op2. Both op1 and op2 are considered to their full own
    precision, which may differ. If one of the operands is NaN, raise
    ValueError.

    Note: This function may be useful to distinguish the three possible
    cases. If you need to distinguish two cases only, it is recommended to use
    the predicate functions like 'greaterequal'; they behave like the IEEE 754
    comparisons, in particular when one or both arguments are NaN.

    """
    op1 = BigFloat._implicit_convert(op1)
    op2 = BigFloat._implicit_convert(op2)
    if is_nan(op1) or is_nan(op2):
        raise ValueError("Cannot perform comparison with NaN.")
    return mpfr.mpfr_cmp(op1, op2)


def cmpabs(op1, op2):
    """
    Compare the absolute values of op1 and op2.

    Return a positive value if op1 > op2, zero if op1 = op2, and a negative
    value if op1 < op2. Both op1 and op2 are considered to their full own
    precision, which may differ. If one of the operands is NaN, raise
    ValueError.

    Note: This function may be useful to distinguish the three possible
    cases. If you need to distinguish two cases only, it is recommended to use
    the predicate functions like 'greaterequal'; they behave like the IEEE 754
    comparisons, in particular when one or both arguments are NaN.

    """
    op1 = BigFloat._implicit_convert(op1)
    op2 = BigFloat._implicit_convert(op2)
    if is_nan(op1) or is_nan(op2):
        raise ValueError("Cannot perform comparison with NaN.")
    return mpfr.mpfr_cmpabs(op1, op2)


def is_nan(x):
    """ Return True if x is a NaN, else False. """

    x = BigFloat._implicit_convert(x)
    return mpfr.mpfr_nan_p(x)


def is_inf(x):
    """ Return True if x is an infinity, else False. """

    x = BigFloat._implicit_convert(x)
    return mpfr.mpfr_inf_p(x)


def is_finite(x):
    """ Return True if x is finite, else False.

    A BigFloat instance is considered to be finite if it is neither an
    infinity or a NaN.

    """
    x = BigFloat._implicit_convert(x)
    return mpfr.mpfr_number_p(x)


def is_zero(x):
    """ Return True if x is a zero, else False. """

    x = BigFloat._implicit_convert(x)
    return mpfr.mpfr_zero_p(x)


def is_regular(x):
    """ Return True if x is finite and nonzero, else False. """

    x = BigFloat._implicit_convert(x)
    return mpfr.mpfr_regular_p(x)


def sgn(x):
    """
    Return the sign of x.

    Return a positive integer if x > 0, 0 if x == 0, and a negative integer if
    x < 0.  Raise ValueError if x is a NaN.

    This function is equivalent to cmp(x, 0), but more efficient.

    """
    x = BigFloat._implicit_convert(x)
    if is_nan(x):
        raise ValueError("Cannot take sign of a NaN.")
    return mpfr.mpfr_sgn(x)


def greater(x, y):
    """
    Return True if x > y and False otherwise.

    This function returns False whenever x and/or y is a NaN.

    """
    x = BigFloat._implicit_convert(x)
    y = BigFloat._implicit_convert(y)
    return mpfr.mpfr_greater_p(x, y)


def greaterequal(x, y):
    """
    Return True if x >= y and False otherwise.

    This function returns False whenever x and/or y is a NaN.

    """
    x = BigFloat._implicit_convert(x)
    y = BigFloat._implicit_convert(y)
    return mpfr.mpfr_greaterequal_p(x, y)


def less(x, y):
    """
    Return True if x < y and False otherwise.

    This function returns False whenever x and/or y is a NaN.

    """
    x = BigFloat._implicit_convert(x)
    y = BigFloat._implicit_convert(y)
    return mpfr.mpfr_less_p(x, y)


def lessequal(x, y):
    """
    Return True if x <= y and False otherwise.

    This function returns False whenever x and/or y is a NaN.

    """
    x = BigFloat._implicit_convert(x)
    y = BigFloat._implicit_convert(y)
    return mpfr.mpfr_lessequal_p(x, y)


def equal(x, y):
    """
    Return True if x == y and False otherwise.

    This function returns False whenever x and/or y is a NaN.

    """
    x = BigFloat._implicit_convert(x)
    y = BigFloat._implicit_convert(y)
    return mpfr.mpfr_equal_p(x, y)


def lessgreater(x, y):
    """
    Return True if x < y or x > y and False otherwise.

    This function returns False whenever x and/or y is a NaN.

    """
    x = BigFloat._implicit_convert(x)
    y = BigFloat._implicit_convert(y)
    return mpfr.mpfr_lessgreater_p(x, y)


def unordered(x, y):
    """
    Return True if x or y is a NaN and False otherwise.

    """
    x = BigFloat._implicit_convert(x)
    y = BigFloat._implicit_convert(y)
    return mpfr.mpfr_unordered_p(x, y)


###############################################################################
# 5.7 Special Functions
###############################################################################

def log(x, context=None):
    """
    Return the natural logarithm of x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_log,
        (BigFloat._implicit_convert(x),),
        context,
    )


def log2(x, context=None):
    """
    Return the base-two logarithm of x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_log2,
        (BigFloat._implicit_convert(x),),
        context,
    )


def log10(x, context=None):
    """
    Return the base-ten logarithm of x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_log10,
        (BigFloat._implicit_convert(x),),
        context,
    )


def exp(x, context=None):
    """
    Return the exponential of x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_exp,
        (BigFloat._implicit_convert(x),),
        context,
    )


def exp2(x, context=None):
    """
    Return two raised to the power x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_exp2,
        (BigFloat._implicit_convert(x),),
        context,
    )


def exp10(x, context=None):
    """
    Return ten raised to the power x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_exp10,
        (BigFloat._implicit_convert(x),),
        context,
    )


def cos(x, context=None):
    """
    Return the cosine of ``x``.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_cos,
        (BigFloat._implicit_convert(x),),
        context,
    )


def sin(x, context=None):
    """
    Return the sine of ``x``.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_sin,
        (BigFloat._implicit_convert(x),),
        context,
    )


def tan(x, context=None):
    """
    Return the tangent of ``x``.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_tan,
        (BigFloat._implicit_convert(x),),
        context,
    )


def sec(x, context=None):
    """
    Return the secant of ``x``.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_sec,
        (BigFloat._implicit_convert(x),),
        context,
    )


def csc(x, context=None):
    """
    Return the cosecant of ``x``.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_csc,
        (BigFloat._implicit_convert(x),),
        context,
    )


def cot(x, context=None):
    """
    Return the cotangent of ``x``.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_cot,
        (BigFloat._implicit_convert(x),),
        context,
    )


def acos(x, context=None):
    """
    Return the inverse cosine of ``x``.

    The mathematically exact result lies in the range [0, π].  However, note
    that as a result of rounding to the current context, it's possible for the
    actual value returned to be fractionally larger than π::

        >>> with precision(12):
        ...     x = acos(-1)
        ...
        >>> print(x)
        3.1416
        >>> x > const_pi()
        True

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_acos,
        (BigFloat._implicit_convert(x),),
        context,
    )


def asin(x, context=None):
    """
    Return the inverse sine of ``x``.

    The mathematically exact result lies in the range [-π/2, π/2].  However,
    note that as a result of rounding to the current context, it's possible
    for the actual value to lie just outside this range.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_asin,
        (BigFloat._implicit_convert(x),),
        context,
    )


def atan(x, context=None):
    """
    Return the inverse tangent of ``x``.

    The mathematically exact result lies in the range [-π/2, π/2].  However,
    note that as a result of rounding to the current context, it's possible
    for the actual value to lie just outside this range.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_atan,
        (BigFloat._implicit_convert(x),),
        context,
    )


def atan2(y, x, context=None):
    """
    Return ``atan(y / x)`` with the appropriate choice of function branch.

    If ``x > 0``, then ``atan2(y, x)`` is mathematically equivalent to ``atan(y
    / x)``.  If ``x < 0`` and ``y > 0``, ``atan(y, x)`` is equivalent to ``π +
    atan(y, x)``.  If ``x < 0`` and ``y < 0``, the result is ``-π + atan(y,
    x)``.

    Geometrically, ``atan2(y, x)`` is the angle (measured counterclockwise, in
    radians) from the positive x-axis to the line segment joining (0, 0) to (x,
    y), in the usual representation of the x-y plane.

    Special values are handled as described in the ISO C99 and IEEE 754-2008
    standards for the atan2 function.  The following examples illustrate the
    rules for positive y; for negative y, apply the symmetry ``atan(-y, x) ==
    -atan(y, x)``.

        >>> finite = positive = 2.3
        >>> negative = -2.3
        >>> inf = BigFloat('inf')

        >>> print(atan2(+0.0, -0.0))     # pi
        3.1415926535897931
        >>> print(atan2(+0.0, +0.0))     # 0
        0
        >>> print(atan2(+0.0, negative)) # pi
        3.1415926535897931
        >>> print(atan2(+0.0, positive)) # 0
        0
        >>> print(atan2(positive, 0.0))  # pi / 2
        1.5707963267948966
        >>> print(atan2(inf, -inf))      # 3*pi / 4
        2.3561944901923448
        >>> print(atan2(inf, inf))       # pi / 4
        0.78539816339744828
        >>> print(atan2(inf, finite))    # pi / 2
        1.5707963267948966
        >>> print(atan2(positive, -inf)) # pi
        3.1415926535897931
        >>> print(atan2(positive, +inf)) # 0
        0

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_atan2,
        (
            BigFloat._implicit_convert(y),
            BigFloat._implicit_convert(x),
        ),
        context,
    )


def cosh(x, context=None):
    """
    Return the hyperbolic cosine of x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_cosh,
        (BigFloat._implicit_convert(x),),
        context,
    )


def sinh(x, context=None):
    """
    Return the hyperbolic sine of x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_sinh,
        (BigFloat._implicit_convert(x),),
        context,
    )


def tanh(x, context=None):
    """
    Return the hyperbolic tangent of x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_tanh,
        (BigFloat._implicit_convert(x),),
        context,
    )


def sech(x, context=None):
    """
    Return the hyperbolic secant of x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_sech,
        (BigFloat._implicit_convert(x),),
        context,
    )


def csch(x, context=None):
    """
    Return the hyperbolic cosecant of x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_csch,
        (BigFloat._implicit_convert(x),),
        context,
    )


def coth(x, context=None):
    """
    Return the hyperbolic cotangent of x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_coth,
        (BigFloat._implicit_convert(x),),
        context,
    )


def acosh(x, context=None):
    """
    Return the inverse hyperbolic cosine of x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_acosh,
        (BigFloat._implicit_convert(x),),
        context,
    )


def asinh(x, context=None):
    """
    Return the inverse hyperbolic sine of x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_asinh,
        (BigFloat._implicit_convert(x),),
        context,
    )


def atanh(x, context=None):
    """
    Return the inverse hyperbolic tangent of x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_atanh,
        (BigFloat._implicit_convert(x),),
        context,
    )


def factorial(x, context=None):
    """
    Return the factorial of the nonnegative integer x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_fac_ui,
        (x,),
        context,
    )


def log1p(x, context=None):
    """
    Return the logarithm of one plus x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_log1p,
        (BigFloat._implicit_convert(x),),
        context,
    )


def expm1(x, context=None):
    """
    Return one less than the exponential of x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_expm1,
        (BigFloat._implicit_convert(x),),
        context,
    )


def eint(x, context=None):
    """
    Return the exponential integral of x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_eint,
        (BigFloat._implicit_convert(x),),
        context,
    )


def li2(x, context=None):
    """
    Return the real part of the dilogarithm of x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_li2,
        (BigFloat._implicit_convert(x),),
        context,
    )


def gamma(x, context=None):
    """
    Return the value of the Gamma function of x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_gamma,
        (BigFloat._implicit_convert(x),),
        context,
    )


def lngamma(x, context=None):
    """
    Return the value of the logarithm of the Gamma function of x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_lngamma,
        (BigFloat._implicit_convert(x),),
        context,
    )


def lgamma(x, context=None):
    """
    Return the logarithm of the absolute value of the Gamma function at x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        lambda rop, op, rnd: mpfr.mpfr_lgamma(rop, op, rnd)[0],
        (BigFloat._implicit_convert(x),),
        context,
    )


def digamma(x, context=None):
    """
    Return the value of the digamma (sometimes also called Psi) function on op.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_digamma,
        (BigFloat._implicit_convert(x),),
        context,
    )


def zeta(x, context=None):
    """
    Return the value of the Riemann zeta function on x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_zeta,
        (BigFloat._implicit_convert(x),),
        context,
    )


def zeta_ui(x, context=None):
    """
    Return the value of the Riemann zeta function at the nonnegative integer x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_zeta_ui,
        (x,),
        context,
    )


def erf(x, context=None):
    """
    Return the value of the error function at x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_erf,
        (BigFloat._implicit_convert(x),),
        context,
    )


def erfc(x, context=None):
    """
    Return the value of the complementary error function at x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_erfc,
        (BigFloat._implicit_convert(x),),
        context,
    )


def j0(x, context=None):
    """
    Return the value of the first kind Bessel function of order 0 at x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_j0,
        (BigFloat._implicit_convert(x),),
        context,
    )


def j1(x, context=None):
    """
    Return the value of the first kind Bessel function of order 1 at x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_j1,
        (BigFloat._implicit_convert(x),),
        context,
    )


def jn(n, x, context=None):
    """
    Return the value of the first kind Bessel function of order ``n`` at ``x``.

    ``n`` should be a Python integer.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_jn,
        (n, BigFloat._implicit_convert(x)),
        context,
    )


def y0(x, context=None):
    """
    Return the value of the second kind Bessel function of order 0 at x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_y0,
        (BigFloat._implicit_convert(x),),
        context,
    )


def y1(x, context=None):
    """
    Return the value of the second kind Bessel function of order 1 at x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_y1,
        (BigFloat._implicit_convert(x),),
        context,
    )


def yn(n, x, context=None):
    """
    Return the value of the second kind Bessel function of order ``n`` at
    ``x``.

    ``n`` should be a Python integer.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_yn,
        (n, BigFloat._implicit_convert(x)),
        context,
    )


def fma(x, y, z, context=None):
    """
    Return (x * y) + z, with a single rounding according to the current
    context.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_fma,
        (
            BigFloat._implicit_convert(x),
            BigFloat._implicit_convert(y),
            BigFloat._implicit_convert(z),
        ),
        context,
    )


def fms(x, y, z, context=None):
    """
    Return (x * y) - z, with a single rounding according to the current
    context.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_fms,
        (
            BigFloat._implicit_convert(x),
            BigFloat._implicit_convert(y),
            BigFloat._implicit_convert(z),
        ),
        context,
    )


def agm(x, y, context=None):
    """
    Return the arithmetic geometric mean of x and y.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_agm,
        (
            BigFloat._implicit_convert(x),
            BigFloat._implicit_convert(y),
        ),
        context,
    )


def hypot(x, y, context=None):
    """
    Return the Euclidean norm of x and y, i.e., the square root of the sum of
    the squares of x and y.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_hypot,
        (
            BigFloat._implicit_convert(x),
            BigFloat._implicit_convert(y),
        ),
        context,
    )


def ai(x, context=None):
    """
    Return the Airy function of x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_ai,
        (BigFloat._implicit_convert(x),),
        context,
    )


def const_log2(context=None):
    """
    Return log(2).

    Returns the natural logarithm of 2, 0.6931471805..., with precision and
    rounding mode taken from the current context.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_const_log2,
        (),
        context,
    )


def const_pi(context=None):
    """
    Return π.

    Returns π = 3.1415926535..., with precision and rounding mode taken from
    the current context.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_const_pi,
        (),
        context,
    )


def const_euler(context=None):
    """
    Return Euler's constant.

    Returns the value of the Euler-Mascheroni constant, 0.5772156649..., with
    precision and rounding mode taken from the current context.  The constant
    is equal to the limit of (1 + 1/2 + 1/3 + ... + 1/n) - log(n) as n
    approaches infinity.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_const_euler,
        (),
        context,
    )


def const_catalan(context=None):
    """
    Return Catalan's constant.

    Returns the value of Catalan's constant 0.9159655941..., with precision and
    rounding mode taken from the current context.  The Catalan constant is
    defined as the limit of the series 1 - 1/3**2 + 1/5**2 - 1/7**2 + 1/9**2 -
    ...

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_const_catalan,
        (),
        context,
    )


###############################################################################
# 5.10 Integer and Remainder Related Functions
###############################################################################

def ceil(x, context=None):
    """
    Return the next higher or equal integer to x.

    If the result is not exactly representable, it will be rounded according to
    the current context.  Note that the rounding step means that it's possible
    for the result to be smaller than ``x``.  For example::

        >>> x = 2**100 + 1
        >>> ceil(2**100 + 1) >= x
        False

    One way to be sure of getting a result that's greater than or equal to
    ``x`` is to use the ``RoundTowardPositive`` rounding mode::

        >>> with RoundTowardPositive:
        ...     x = 2**100 + 1
        ...     ceil(x) >= x
        ...
        True

    Similar comments apply to the :func:`floor`, :func:`round` and
    :func:`trunc` functions.

    .. note::

       This function corresponds to the MPFR function ``mpfr_rint_ceil``,
       not to ``mpfr_ceil``.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_rint_ceil,
        (BigFloat._implicit_convert(x),),
        context,
    )


def floor(x, context=None):
    """
    Return the next lower or equal integer to x.

    If the result is not exactly representable, it will be rounded according to
    the current context.

    Note that it's possible for the result to be larger than ``x``.  See the
    documentation of the :func:`ceil` function for more information.

    .. note::

       This function corresponds to the MPFR function ``mpfr_rint_floor``,
       not to ``mpfr_floor``.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_rint_floor,
        (BigFloat._implicit_convert(x),),
        context,
    )


def round(x, context=None):
    """
    Return the nearest integer to x, rounding halfway cases *away from zero*.

    If the result is not exactly representable, it will be rounded according to
    the current context.

    .. note::

       This function corresponds to the MPFR function ``mpfr_rint_round``, not
       to ``mpfr_round``.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_rint_round,
        (BigFloat._implicit_convert(x),),
        context,
    )


def trunc(x, context=None):
    """
    Return the next integer towards zero.

    If the result is not exactly representable, it will be rounded according to
    the current context.

    .. note::

       This function corresponds to the MPFR function ``mpfr_rint_trunc``,
       not to ``mpfr_trunc``.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_rint_trunc,
        (BigFloat._implicit_convert(x),),
        context,
    )


def frac(x, context=None):
    """
    Return the fractional part of ``x``.

    The result has the same sign as ``x``.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_frac,
        (BigFloat._implicit_convert(x),),
        context,
    )


def mod(x, y, context=None):
    """
    Return ``x`` reduced modulo ``y``.

    Returns the value of x - n * y, where n is the integer quotient of x
    divided by y, rounded toward zero.

    Special values are handled as described in Section F.9.7.1 of the ISO C99
    standard: If x is infinite or y is zero, the result is NaN. If y is
    infinite and x is finite, the result is x rounded to the current context.
    If the result is zero, it has the sign of x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_fmod,
        (
            BigFloat._implicit_convert(x),
            BigFloat._implicit_convert(y),
        ),
        context,
    )


def remainder(x, y, context=None):
    """
    Return x reduced modulo y.

    Returns the value of x - n * y, where n is the integer quotient of x
    divided by y, rounded to the nearest integer (ties rounded to even).

    Special values are handled as described in Section F.9.7.1 of the ISO C99
    standard: If x is infinite or y is zero, the result is NaN. If y is
    infinite and x is finite, the result is x (rounded to the current
    context). If the result is zero, it has the sign of x.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_remainder,
        (
            BigFloat._implicit_convert(x),
            BigFloat._implicit_convert(y),
        ),
        context,
    )


def is_integer(x):
    """ Return True if x is an exact integer, else False. """

    x = BigFloat._implicit_convert(x)
    return mpfr.mpfr_integer_p(x)


###############################################################################
# 5.12 Miscellaneous Functions
###############################################################################

def min(x, y, context=None):
    """
    Return the minimum of x and y.

    If x and y are both NaN, return NaN. If exactly one of x and y is NaN,
    return the non-NaN value. If x and y are zeros of different signs, return
    −0.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_min,
        (
            BigFloat._implicit_convert(x),
            BigFloat._implicit_convert(y),
        ),
        context,
    )


def max(x, y, context=None):
    """
    Return the maximum of x and y.

    If x and y are both NaN, return NaN. If exactly one of x and y is NaN,
    return the non-NaN value. If x and y are zeros of different signs, return
    +0.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_max,
        (
            BigFloat._implicit_convert(x),
            BigFloat._implicit_convert(y),
        ),
        context,
    )


def is_negative(x):
    """ Return True if x has its sign bit set, else False.

    Note that this function returns True for negative zeros.

    """
    x = BigFloat._implicit_convert(x)
    return mpfr.mpfr_signbit(x)


def copysign(x, y, context=None):
    """
    Return a new BigFloat object with the magnitude of x but the sign of y.

    """
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_copysign,
        (
            BigFloat._implicit_convert(x),
            BigFloat._implicit_convert(y),
        ),
        context,
    )


# unary arithmetic operations
BigFloat.__pos__ = pos
BigFloat.__neg__ = neg
BigFloat.__abs__ = abs

# binary arithmetic operations
BigFloat.__add__ = _binop(add)
BigFloat.__sub__ = _binop(sub)
BigFloat.__mul__ = _binop(mul)
BigFloat.__div__ = BigFloat.__truediv__ = _binop(div)
BigFloat.__pow__ = _binop(pow)

# and their reverse operations
BigFloat.__radd__ = _rbinop(add)
BigFloat.__rsub__ = _rbinop(sub)
BigFloat.__rmul__ = _rbinop(mul)
BigFloat.__rdiv__ = BigFloat.__rtruediv__ = _rbinop(div)
BigFloat.__rpow__ = _rbinop(pow)

if (mpfr.MPFR_VERSION_MAJOR, mpfr.MPFR_VERSION_MINOR) >= (2, 4):
    BigFloat.__mod__ = _binop(mod)
    BigFloat.__rmod__ = _rbinop(mod)

# comparisons
BigFloat.__eq__ = _binop(equal)
BigFloat.__le__ = _binop(lessequal)
BigFloat.__lt__ = _binop(less)
BigFloat.__ge__ = _binop(greaterequal)
BigFloat.__gt__ = _binop(greater)

MPFR_VERSION_MAJOR = mpfr.MPFR_VERSION_MAJOR
MPFR_VERSION_MINOR = mpfr.MPFR_VERSION_MINOR