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 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258
|
package Math::BigFloat;
#
# Mike grinned. 'Two down, infinity to go' - Mike Nostrus in 'Before and After'
#
# The following hash values are used internally:
#
# sign : "+", "-", "+inf", "-inf", or "NaN"
# _m : absolute value of mantissa ($LIB thingy)
# _es : sign of exponent ("+" or "-")
# _e : absolute value of exponent ($LIB thingy)
# accuracy : accuracy (scalar)
# precision : precision (scalar)
use 5.006001;
use strict;
use warnings;
use Carp qw< carp croak >;
use Scalar::Util qw< blessed >;
use Math::BigInt qw< >;
our $VERSION = '2.005002';
$VERSION =~ tr/_//d;
require Exporter;
our @ISA = qw< Math::BigInt >;
our @EXPORT_OK = qw< bpi >;
use overload
# overload key: with_assign
'+' => sub { $_[0] -> copy() -> badd($_[1]); },
'-' => sub { my $c = $_[0] -> copy();
$_[2] ? $c -> bneg() -> badd($_[1])
: $c -> bsub($_[1]); },
'*' => sub { $_[0] -> copy() -> bmul($_[1]); },
'/' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bdiv($_[0])
: $_[0] -> copy() -> bdiv($_[1]); },
'%' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bmod($_[0])
: $_[0] -> copy() -> bmod($_[1]); },
'**' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bpow($_[0])
: $_[0] -> copy() -> bpow($_[1]); },
'<<' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bblsft($_[0])
: $_[0] -> copy() -> bblsft($_[1]); },
'>>' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bbrsft($_[0])
: $_[0] -> copy() -> bbrsft($_[1]); },
# overload key: assign
'+=' => sub { $_[0] -> badd($_[1]); },
'-=' => sub { $_[0] -> bsub($_[1]); },
'*=' => sub { $_[0] -> bmul($_[1]); },
'/=' => sub { scalar $_[0] -> bdiv($_[1]); },
'%=' => sub { $_[0] -> bmod($_[1]); },
'**=' => sub { $_[0] -> bpow($_[1]); },
'<<=' => sub { $_[0] -> bblsft($_[1]); },
'>>=' => sub { $_[0] -> bbrsft($_[1]); },
# 'x=' => sub { },
# '.=' => sub { },
# overload key: num_comparison
'<' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> blt($_[0])
: $_[0] -> blt($_[1]); },
'<=' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> ble($_[0])
: $_[0] -> ble($_[1]); },
'>' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bgt($_[0])
: $_[0] -> bgt($_[1]); },
'>=' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bge($_[0])
: $_[0] -> bge($_[1]); },
'==' => sub { $_[0] -> beq($_[1]); },
'!=' => sub { $_[0] -> bne($_[1]); },
# overload key: 3way_comparison
'<=>' => sub { my $cmp = $_[0] -> bcmp($_[1]);
defined($cmp) && $_[2] ? -$cmp : $cmp; },
'cmp' => sub { $_[2] ? "$_[1]" cmp $_[0] -> bstr()
: $_[0] -> bstr() cmp "$_[1]"; },
# overload key: str_comparison
# 'lt' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bstrlt($_[0])
# : $_[0] -> bstrlt($_[1]); },
#
# 'le' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bstrle($_[0])
# : $_[0] -> bstrle($_[1]); },
#
# 'gt' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bstrgt($_[0])
# : $_[0] -> bstrgt($_[1]); },
#
# 'ge' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bstrge($_[0])
# : $_[0] -> bstrge($_[1]); },
#
# 'eq' => sub { $_[0] -> bstreq($_[1]); },
#
# 'ne' => sub { $_[0] -> bstrne($_[1]); },
# overload key: binary
'&' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> band($_[0])
: $_[0] -> copy() -> band($_[1]); },
'&=' => sub { $_[0] -> band($_[1]); },
'|' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bior($_[0])
: $_[0] -> copy() -> bior($_[1]); },
'|=' => sub { $_[0] -> bior($_[1]); },
'^' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bxor($_[0])
: $_[0] -> copy() -> bxor($_[1]); },
'^=' => sub { $_[0] -> bxor($_[1]); },
# '&.' => sub { },
# '&.=' => sub { },
# '|.' => sub { },
# '|.=' => sub { },
# '^.' => sub { },
# '^.=' => sub { },
# overload key: unary
'neg' => sub { $_[0] -> copy() -> bneg(); },
# '!' => sub { },
'~' => sub { $_[0] -> copy() -> bnot(); },
# '~.' => sub { },
# overload key: mutators
'++' => sub { $_[0] -> binc() },
'--' => sub { $_[0] -> bdec() },
# overload key: func
'atan2' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> batan2($_[0])
: $_[0] -> copy() -> batan2($_[1]); },
'cos' => sub { $_[0] -> copy() -> bcos(); },
'sin' => sub { $_[0] -> copy() -> bsin(); },
'exp' => sub { $_[0] -> copy() -> bexp($_[1]); },
'abs' => sub { $_[0] -> copy() -> babs(); },
'log' => sub { $_[0] -> copy() -> blog(); },
'sqrt' => sub { $_[0] -> copy() -> bsqrt(); },
'int' => sub { $_[0] -> copy() -> bint(); },
# overload key: conversion
'bool' => sub { $_[0] -> is_zero() ? '' : 1; },
'""' => sub { $_[0] -> bstr(); },
'0+' => sub { $_[0] -> numify(); },
'=' => sub { $_[0] -> copy(); },
;
##############################################################################
# global constants, flags and assorted stuff
# the following are public, but their usage is not recommended. Use the
# accessor methods instead.
# class constants, use Class->constant_name() to access
# one of 'even', 'odd', '+inf', '-inf', 'zero', 'trunc' or 'common'
our $accuracy = undef;
our $precision = undef;
our $round_mode = 'even';
our $div_scale = 40;
our $upgrade = undef;
our $downgrade = undef;
our $_trap_nan = 0; # croak on NaNs?
our $_trap_inf = 0; # croak on Infs?
my $nan = 'NaN'; # constant for easier life
my $LIB = Math::BigInt -> config('lib'); # math backend library
# Has import() been called yet? This variable is needed to make "require" work.
my $IMPORT = 0;
# some digits of accuracy for blog(undef, 10); which we use in blog() for speed
my $LOG_10 =
'2.3025850929940456840179914546843642076011014886287729760333279009675726097';
my $LOG_10_A = length($LOG_10)-1;
# ditto for log(2)
my $LOG_2 =
'0.6931471805599453094172321214581765680755001343602552541206800094933936220';
my $LOG_2_A = length($LOG_2)-1;
my $HALF = '0.5'; # made into an object if nec.
##############################################################################
# the old code had $rnd_mode, so we need to support it, too
our $rnd_mode;
our $AUTOLOAD;
sub TIESCALAR {
my ($class) = @_;
bless \$round_mode, $class;
}
sub FETCH {
return $round_mode;
}
sub STORE {
$rnd_mode = (ref $_[0]) -> round_mode($_[1]);
}
BEGIN {
*objectify = \&Math::BigInt::objectify;
# when someone sets $rnd_mode, we catch this and check the value to see
# whether it is valid or not.
$rnd_mode = 'even';
tie $rnd_mode, 'Math::BigFloat';
*as_number = \&as_int;
}
sub DESTROY {
# going through AUTOLOAD for every DESTROY is costly, avoid it by empty sub
}
sub AUTOLOAD {
# Make fxxx() work by mapping fxxx() to Math::BigFloat::bxxx().
my $name = $AUTOLOAD;
$name =~ s/^(.*):://; # strip package name
my $class = $1 || __PACKAGE__;
$class -> import() if $IMPORT == 0;
# E.g., "fabs" -> "babs", but "is_neg" -> "is_neg"
my $bname = $name;
$bname =~ s/^f/b/;
# Map, e.g., Math::BigFloat::fabs() to Math::BigFloat::babs()
if ($bname ne $name && Math::BigFloat -> can($bname)) {
no strict 'refs';
return &{"Math::BigFloat::$bname"}(@_);
}
# Map, e.g., Math::BigFloat::babs() to Math::BigInt::babs()
elsif (Math::BigInt -> can($bname)) {
no strict 'refs';
return &{"Math::BigInt::$bname"}(@_);
}
else {
croak("Can't call $class->$name(), not a valid method");
}
}
##############################################################################
# Compare the following function with @ISA above. This inheritance mess needs a
# clean up. When doing so, also consider the BEGIN block and the AUTOLOAD code.
# Fixme!
sub isa {
my ($self, $class) = @_;
return if $class =~ /^Math::BigInt/; # we aren't one of these
UNIVERSAL::isa($self, $class);
}
sub config {
my $self = shift;
my $class = ref($self) || $self || __PACKAGE__;
# Getter/accessor.
if (@_ == 1 && ref($_[0]) ne 'HASH') {
my $param = shift;
return $class if $param eq 'class';
return $LIB if $param eq 'with';
return $self -> SUPER::config($param);
}
# Setter.
my $cfg = $self -> SUPER::config(@_);
# We need only to override the ones that are different from our parent.
unless (ref($self)) {
$cfg->{class} = $class;
$cfg->{with} = $LIB;
}
$cfg;
}
###############################################################################
# Constructor methods
###############################################################################
sub new {
# Create a new Math::BigFloat object from a string or another Math::BigInt,
# Math::BigFloat, or Math::BigRat object. See hash keys documented at top.
my $self = shift;
my $selfref = ref $self;
my $class = $selfref || $self;
# Make "require" work.
$class -> import() if $IMPORT == 0;
# Calling new() with no input arguments has been discouraged for more than
# 10 years, but people apparently still use it, so we still support it.
return $class -> bzero() unless @_;
my ($wanted, @r) = @_;
if (!defined($wanted)) {
#if (warnings::enabled("uninitialized")) {
# warnings::warn("uninitialized",
# "Use of uninitialized value in new()");
#}
return $class -> bzero(@r);
}
if (!ref($wanted) && $wanted eq "") {
#if (warnings::enabled("numeric")) {
# warnings::warn("numeric",
# q|Argument "" isn't numeric in new()|);
#}
#return $class -> bzero(@r);
return $class -> bnan(@r);
}
# Initialize a new object.
$self = bless {}, $class;
# See if $wanted is an object that is a Math::BigFloat or can convert
# itself to a Math::BigFloat.
if (defined(blessed($wanted)) && $wanted -> can('as_float')) {
my $tmp = $wanted -> as_float(@r);
for my $attr ('sign', '_m', '_es', '_e') {
$self -> {$attr} = $tmp -> {$attr};
}
return $self -> round(@r);
}
# From now on we only work on the stringified version of $wanted, so
# stringify it once and for all.
$wanted = "$wanted";
# Shortcut for simple forms like '123' that have no trailing zeros.
# Trailing zeros would require a non-zero exponent.
if ($wanted =~
/ ^
\s* # optional leading whitespace
( [+-]? ) # optional sign
0* # optional leading zeros
( [1-9] (?: [0-9]* [1-9] )? ) # significand
\s* # optional trailing whitespace
$
/x)
{
my $dng = $class -> downgrade();
return $dng -> new($1 . $2) if $dng && $dng ne $class;
$self->{sign} = $1 || '+';
$self->{_m} = $LIB -> _new($2);
$self->{_es} = '+';
$self->{_e} = $LIB -> _zero();
$self -> round(@r)
unless @r >= 2 && !defined $r[0] && !defined $r[1];
return $self;
}
# Handle Infs.
if ($wanted =~ / ^
\s*
( [+-]? )
inf (?: inity )?
\s*
\z
/ix)
{
my $sgn = $1 || '+';
return $class -> binf($sgn, @r);
}
# Handle explicit NaNs (not the ones returned due to invalid input).
if ($wanted =~ / ^
\s*
( [+-]? )
nan
\s*
\z
/ix)
{
return $class -> bnan(@r);
}
my @parts;
if (
# Handle hexadecimal numbers. We auto-detect hexadecimal numbers if
# they have a "0x", "0X", "x", or "X" prefix, cf. CORE::oct().
$wanted =~ /^\s*[+-]?0?[Xx]/ and
@parts = $class -> _hex_str_to_flt_lib_parts($wanted)
or
# Handle octal numbers. We auto-detect octal numbers if they have a
# "0o", "0O", "o", "O" prefix, cf. CORE::oct().
$wanted =~ /^\s*[+-]?0?[Oo]/ and
@parts = $class -> _oct_str_to_flt_lib_parts($wanted)
or
# Handle binary numbers. We auto-detect binary numbers if they have a
# "0b", "0B", "b", or "B" prefix, cf. CORE::oct().
$wanted =~ /^\s*[+-]?0?[Bb]/ and
@parts = $class -> _bin_str_to_flt_lib_parts($wanted)
or
# At this point, what is left are decimal numbers that aren't handled
# above and octal floating point numbers that don't have any of the
# "0o", "0O", "o", or "O" prefixes. First see if it is a decimal
# number.
@parts = $class -> _dec_str_to_flt_lib_parts($wanted)
or
# See if it is an octal floating point number. The extra check is
# included because _oct_str_to_flt_lib_parts() accepts octal numbers
# that don't have a prefix (this is needed to make it work with, e.g.,
# from_oct() that don't require a prefix). However, Perl requires a
# prefix for octal floating point literals. For example, "1p+0" is not
# valid, but "01p+0" and "0__1p+0" are.
$wanted =~ /^\s*[+-]?0_*\d/ and
@parts = $class -> _oct_str_to_flt_lib_parts($wanted))
{
($self->{sign}, $self->{_m}, $self->{_es}, $self->{_e}) = @parts;
$self -> round(@r)
unless @r >= 2 && !defined($r[0]) && !defined($r[1]);
$self -> _dng() if ($self -> is_int() ||
$self -> is_inf() ||
$self -> is_nan());
return $self;
}
# If we get here, the value is neither a valid decimal, binary, octal, or
# hexadecimal number. It is not an explicit Inf or a NaN either.
return $class -> bnan(@r);
}
sub from_dec {
my $self = shift;
my $selfref = ref $self;
my $class = $selfref || $self;
# Make "require" work.
$class -> import() if $IMPORT == 0;
# Don't modify constant (read-only) objects.
return $self if $selfref && $self -> modify('from_dec');
my $str = shift;
my @r = @_;
if (my @parts = $class -> _dec_str_to_flt_lib_parts($str)) {
# If called as a class method, initialize a new object.
unless ($selfref) {
$self = bless {}, $class;
#$self -> _init();
}
($self->{sign}, $self->{_m}, $self->{_es}, $self->{_e}) = @parts;
$self -> round(@r)
unless @r >= 2 && !defined($r[0]) && !defined($r[1]);
$self -> _dng() if ($self -> is_int() ||
$self -> is_inf() ||
$self -> is_nan());
return $self;
}
return $self -> bnan(@r);
}
sub from_hex {
my $self = shift;
my $selfref = ref $self;
my $class = $selfref || $self;
# Make "require" work.
$class -> import() if $IMPORT == 0;
# Don't modify constant (read-only) objects.
return $self if $selfref && $self -> modify('from_hex');
my $str = shift;
my @r = @_;
if (my @parts = $class -> _hex_str_to_flt_lib_parts($str)) {
# If called as a class method, initialize a new object.
unless ($selfref) {
$self = bless {}, $class;
#$self -> _init();
}
($self->{sign}, $self->{_m}, $self->{_es}, $self->{_e}) = @parts;
$self -> round(@r)
unless @r >= 2 && !defined($r[0]) && !defined($r[1]);
$self -> _dng() if ($self -> is_int() ||
$self -> is_inf() ||
$self -> is_nan());
return $self;
}
return $self -> bnan(@r);
}
sub from_oct {
my $self = shift;
my $selfref = ref $self;
my $class = $selfref || $self;
# Make "require" work.
$class -> import() if $IMPORT == 0;
# Don't modify constant (read-only) objects.
return $self if $selfref && $self -> modify('from_oct');
my $str = shift;
my @r = @_;
if (my @parts = $class -> _oct_str_to_flt_lib_parts($str)) {
# If called as a class method, initialize a new object.
unless ($selfref) {
$self = bless {}, $class;
#$self -> _init();
}
($self->{sign}, $self->{_m}, $self->{_es}, $self->{_e}) = @parts;
$self -> round(@r)
unless @r >= 2 && !defined($r[0]) && !defined($r[1]);
$self -> _dng() if ($self -> is_int() ||
$self -> is_inf() ||
$self -> is_nan());
return $self;
}
return $self -> bnan(@r);
}
sub from_bin {
my $self = shift;
my $selfref = ref $self;
my $class = $selfref || $self;
# Make "require" work.
$class -> import() if $IMPORT == 0;
# Don't modify constant (read-only) objects.
return $self if $selfref && $self -> modify('from_bin');
my $str = shift;
my @r = @_;
if (my @parts = $class -> _bin_str_to_flt_lib_parts($str)) {
# If called as a class method, initialize a new object.
unless ($selfref) {
$self = bless {}, $class;
#$self -> _init();
}
($self->{sign}, $self->{_m}, $self->{_es}, $self->{_e}) = @parts;
$self -> round(@r)
unless @r >= 2 && !defined($r[0]) && !defined($r[1]);
$self -> _dng() if ($self -> is_int() ||
$self -> is_inf() ||
$self -> is_nan());
return $self;
}
return $self -> bnan(@r);
}
sub from_bytes {
my $self = shift;
my $selfref = ref $self;
my $class = $selfref || $self;
# Make "require" work.
$class -> import() if $IMPORT == 0;
# Don't modify constant (read-only) objects.
return $self if $selfref && $self -> modify('from_bytes');
my $str = shift;
my @r = @_;
# If called as a class method, initialize a new object.
$self = $class -> bzero(@r) unless $selfref;
$self -> {sign} = "+";
$self -> {_m} = $LIB -> _from_bytes($str);
$self -> {_es} = "+";
$self -> {_e} = $LIB -> _zero();
$self -> bnorm();
$self -> _dng();
return $self;
}
sub from_ieee754 {
my $self = shift;
my $selfref = ref $self;
my $class = $selfref || $self;
# Make "require" work.
$class -> import() if $IMPORT == 0;
# Don't modify constant (read-only) objects.
return $self if $selfref && $self -> modify('from_ieee754');
my $in = shift; # input string (or raw bytes)
my $format = shift; # format ("binary32", "decimal64" etc.)
my $enc; # significand encoding (applies only to decimal)
my $k; # storage width in bits
my $b; # base
my @r = @_; # rounding parameters, if any
if ($format =~ /^binary(\d+)\z/) {
$k = $1;
$b = 2;
} elsif ($format =~ /^decimal(\d+)(dpd|bcd)?\z/) {
$k = $1;
$b = 10;
$enc = $2 || 'dpd'; # default is dencely-packed decimals (DPD)
} elsif ($format eq 'half') {
$k = 16;
$b = 2;
} elsif ($format eq 'single') {
$k = 32;
$b = 2;
} elsif ($format eq 'double') {
$k = 64;
$b = 2;
} elsif ($format eq 'quadruple') {
$k = 128;
$b = 2;
} elsif ($format eq 'octuple') {
$k = 256;
$b = 2;
} elsif ($format eq 'sexdecuple') {
$k = 512;
$b = 2;
}
if ($b == 2) {
# Get the parameters for this format.
my $p; # precision (in bits)
my $t; # number of bits in significand
my $w; # number of bits in exponent
if ($k == 16) { # binary16 (half-precision)
$p = 11;
$t = 10;
$w = 5;
} elsif ($k == 32) { # binary32 (single-precision)
$p = 24;
$t = 23;
$w = 8;
} elsif ($k == 64) { # binary64 (double-precision)
$p = 53;
$t = 52;
$w = 11;
} else { # binaryN (quadruple-precision and above)
if ($k < 128 || $k != 32 * sprintf('%.0f', $k / 32)) {
croak "Number of bits must be 16, 32, 64, or >= 128 and",
" a multiple of 32";
}
$p = $k - sprintf('%.0f', 4 * log($k) / log(2)) + 13;
$t = $p - 1;
$w = $k - $t - 1;
}
# The maximum exponent, minimum exponent, and exponent bias.
my $emax = $class -> new(2) -> bpow($w - 1) -> bdec();
my $emin = 1 - $emax;
my $bias = $emax;
# Undefined input.
unless (defined $in) {
carp("Input is undefined");
return $self -> bzero(@r);
}
# Make sure input string is a string of zeros and ones.
my $len = CORE::length $in;
if (8 * $len == $k) { # bytes
$in = unpack "B*", $in;
} elsif (4 * $len == $k) { # hexadecimal
if ($in =~ /([^\da-f])/i) {
croak "Illegal hexadecimal digit '$1'";
}
$in = unpack "B*", pack "H*", $in;
} elsif ($len == $k) { # bits
if ($in =~ /([^01])/) {
croak "Illegal binary digit '$1'";
}
} else {
croak "Unknown input -- $in";
}
# Split bit string into sign, exponent, and mantissa/significand.
my $sign = substr($in, 0, 1) eq '1' ? '-' : '+';
my $expo = $class -> from_bin(substr($in, 1, $w));
my $mant = $class -> from_bin(substr($in, $w + 1));
my $x;
$expo -> bsub($bias); # subtract bias
if ($expo < $emin) { # zero and subnormals
if ($mant == 0) { # zero
$x = $class -> bzero();
} else { # subnormals
# compute (1/$b)**(N) rather than ($b)**(-N)
$x = $class -> new("0.5"); # 1/$b
$x -> bpow($bias + $t - 1) -> bmul($mant);
$x -> bneg() if $sign eq '-';
}
}
elsif ($expo > $emax) { # inf and nan
if ($mant == 0) { # inf
$x = $class -> binf($sign);
} else { # nan
$x = $class -> bnan(@r);
}
}
else { # normals
$mant = $class -> new(2) -> bpow($t) -> badd($mant);
if ($expo < $t) {
# compute (1/$b)**(N) rather than ($b)**(-N)
$x = $class -> new("0.5"); # 1/$b
$x -> bpow($t - $expo) -> bmul($mant);
} else {
$x = $class -> new(2);
$x -> bpow($expo - $t) -> bmul($mant);
}
$x -> bneg() if $sign eq '-';
}
if ($selfref) {
$self -> {sign} = $x -> {sign};
$self -> {_m} = $x -> {_m};
$self -> {_es} = $x -> {_es};
$self -> {_e} = $x -> {_e};
} else {
$self = $x;
}
$self -> round(@r);
$self -> _dng() if ($self -> is_int() ||
$self -> is_inf() ||
$self -> is_nan());
return $self;
}
croak("The format '$format' is not yet supported.");
}
sub from_base {
my $self = shift;
my $selfref = ref $self;
my $class = $selfref || $self;
# Make "require" work.
$class -> import() if $IMPORT == 0;
# Don't modify constant (read-only) objects.
return $self if $selfref && $self -> modify('from_base');
my ($str, $base, $cs, @r) = @_; # $cs is the collation sequence
$base = $class -> new($base) unless ref($base);
croak("the base must be a finite integer >= 2")
if $base < 2 || ! $base -> is_int();
# If called as a class method, initialize a new object.
$self = $class -> bzero() unless $selfref;
# If no collating sequence is given, pass some of the conversions to
# methods optimized for those cases.
unless (defined $cs) {
return $self -> from_bin($str, @r) if $base == 2;
return $self -> from_oct($str, @r) if $base == 8;
return $self -> from_hex($str, @r) if $base == 16;
return $self -> from_dec($str, @r) if $base == 10;
}
croak("from_base() requires a newer version of the $LIB library.")
unless $LIB -> can('_from_base');
my $base_lib = $LIB -> _lsft($LIB -> _copy($base->{_m}), $base->{_e}, 10);
$self -> {sign} = '+';
$self -> {_m} = $LIB->_from_base($str, $base_lib,
defined($cs) ? $cs : ());
$self -> {_es} = "+";
$self -> {_e} = $LIB->_zero();
$self -> bnorm();
$self -> bround(@r);
$self -> _dng();
return $self;
}
sub bzero {
# create/assign '+0'
# Class::method(...) -> Class->method(...)
unless (@_ && (defined(blessed($_[0])) && $_[0] -> isa(__PACKAGE__) ||
$_[0] =~ /^[a-z]\w*(?:::[a-z]\w*)*$/i))
{
#carp "Using ", (caller(0))[3], "() as a function is deprecated;",
# " use is as a method instead";
unshift @_, __PACKAGE__;
}
my $self = shift;
my $selfref = ref $self;
my $class = $selfref || $self;
# Make "require" work.
$class -> import() if $IMPORT == 0;
# Don't modify constant (read-only) objects.
return $self if $selfref && $self -> modify('bzero');
my $dng = $class -> downgrade();
if ($dng && $dng ne $class) {
return $self -> _dng() -> bzero(@_) if $selfref;
return $dng -> bzero(@_);
}
# Get the rounding parameters, if any.
my @r = @_;
# If called as a class method, initialize a new object.
$self = bless {}, $class unless $selfref;
$self -> {sign} = '+';
$self -> {_m} = $LIB -> _zero();
$self -> {_es} = '+';
$self -> {_e} = $LIB -> _zero();
# If rounding parameters are given as arguments, use them. If no rounding
# parameters are given, and if called as a class method initialize the new
# instance with the class variables.
#return $self -> round(@r); # this should work, but doesnt; fixme!
if (@r) {
if (@r >= 2 && defined($r[0]) && defined($r[1])) {
carp "can't specify both accuracy and precision";
return $self -> bnan();
}
$self->{accuracy} = $r[0];
$self->{precision} = $r[1];
} else {
unless($selfref) {
$self->{accuracy} = $class -> accuracy();
$self->{precision} = $class -> precision();
}
}
return $self;
}
sub bone {
# Create or assign '+1' (or -1 if given sign '-').
# Class::method(...) -> Class->method(...)
unless (@_ && (defined(blessed($_[0])) && $_[0] -> isa(__PACKAGE__) ||
$_[0] =~ /^[a-z]\w*(?:::[a-z]\w*)*$/i))
{
#carp "Using ", (caller(0))[3], "() as a function is deprecated;",
# " use is as a method instead";
unshift @_, __PACKAGE__;
}
my $self = shift;
my $selfref = ref $self;
my $class = $selfref || $self;
# Make "require" work.
$class -> import() if $IMPORT == 0;
# Don't modify constant (read-only) objects.
return $self if $selfref && $self -> modify('bone');
my $dng = $class -> downgrade();
if ($dng && $dng ne $class) {
return $self -> _dng() -> bone(@_) if $selfref;
return $dng -> bone(@_);
}
# Get the sign.
my $sign = '+'; # default is to return +1
if (defined($_[0]) && $_[0] =~ /^\s*([+-])\s*$/) {
$sign = $1;
shift;
}
# Get the rounding parameters, if any.
my @r = @_;
# If called as a class method, initialize a new object.
$self = bless {}, $class unless $selfref;
$self -> {sign} = $sign;
$self -> {_m} = $LIB -> _one();
$self -> {_es} = '+';
$self -> {_e} = $LIB -> _zero();
# If rounding parameters are given as arguments, use them. If no rounding
# parameters are given, and if called as a class method initialize the new
# instance with the class variables.
#return $self -> round(@r); # this should work, but doesnt; fixme!
if (@r) {
if (@r >= 2 && defined($r[0]) && defined($r[1])) {
carp "can't specify both accuracy and precision";
return $self -> bnan();
}
$self->{accuracy} = $_[0];
$self->{precision} = $_[1];
} else {
unless($selfref) {
$self->{accuracy} = $class -> accuracy();
$self->{precision} = $class -> precision();
}
}
return $self;
}
sub binf {
# create/assign a '+inf' or '-inf'
# Class::method(...) -> Class->method(...)
unless (@_ && (defined(blessed($_[0])) && $_[0] -> isa(__PACKAGE__) ||
$_[0] =~ /^[a-z]\w*(?:::[a-z]\w*)*$/i))
{
#carp "Using ", (caller(0))[3], "() as a function is deprecated;",
# " use is as a method instead";
unshift @_, __PACKAGE__;
}
my $self = shift;
my $selfref = ref $self;
my $class = $selfref || $self;
{
no strict 'refs';
if (${"${class}::_trap_inf"}) {
croak("Tried to create +-inf in $class->binf()");
}
}
# Make "require" work.
$class -> import() if $IMPORT == 0;
# Don't modify constant (read-only) objects.
return $self if $selfref && $self -> modify('binf');
# Get the sign.
my $sign = '+'; # default is to return positive infinity
if (defined($_[0]) && $_[0] =~ /^\s*([+-])(inf|$)/i) {
$sign = $1;
shift;
}
# Get the rounding parameters, if any.
my @r = @_;
# Downgrade?
my $dng = $class -> downgrade();
if ($dng && $dng ne $class) {
return $self -> _dng() -> binf($sign, @r) if $selfref;
return $dng -> binf($sign, @r);
}
# If called as a class method, initialize a new object.
$self = bless {}, $class unless $selfref;
$self -> {sign} = $sign . 'inf';
$self -> {_m} = $LIB -> _zero();
$self -> {_es} = '+';
$self -> {_e} = $LIB -> _zero();
# If rounding parameters are given as arguments, use them. If no rounding
# parameters are given, and if called as a class method initialize the new
# instance with the class variables.
#return $self -> round(@r); # this should work, but doesnt; fixme!
if (@r) {
if (@r >= 2 && defined($r[0]) && defined($r[1])) {
carp "can't specify both accuracy and precision";
return $self -> bnan();
}
$self->{accuracy} = $r[0];
$self->{precision} = $r[1];
} else {
unless($selfref) {
$self->{accuracy} = $class -> accuracy();
$self->{precision} = $class -> precision();
}
}
return $self;
}
sub bnan {
# create/assign a 'NaN'
# Class::method(...) -> Class->method(...)
unless (@_ && (defined(blessed($_[0])) && $_[0] -> isa(__PACKAGE__) ||
$_[0] =~ /^[a-z]\w*(?:::[a-z]\w*)*$/i))
{
#carp "Using ", (caller(0))[3], "() as a function is deprecated;",
# " use is as a method instead";
unshift @_, __PACKAGE__;
}
my $self = shift;
my $selfref = ref $self;
my $class = $selfref || $self;
{
no strict 'refs';
if (${"${class}::_trap_nan"}) {
croak("Tried to create NaN in $class->bnan()");
}
}
# Make "require" work.
$class -> import() if $IMPORT == 0;
# Don't modify constant (read-only) objects.
return $self if $selfref && $self -> modify('bnan');
my $dng = $class -> downgrade();
if ($dng && $dng ne $class) {
return $self -> _dng() -> bnan(@_) if $selfref;
return $dng -> bnan(@_);
}
# Get the rounding parameters, if any.
my @r = @_;
# If called as a class method, initialize a new object.
$self = bless {}, $class unless $selfref;
$self -> {sign} = $nan;
$self -> {_m} = $LIB -> _zero();
$self -> {_es} = '+';
$self -> {_e} = $LIB -> _zero();
# If rounding parameters are given as arguments, use them. If no rounding
# parameters are given, and if called as a class method initialize the new
# instance with the class variables.
#return $self -> round(@r); # this should work, but doesnt; fixme!
if (@r) {
if (@r >= 2 && defined($r[0]) && defined($r[1])) {
carp "can't specify both accuracy and precision";
return $self -> bnan();
}
$self->{accuracy} = $r[0];
$self->{precision} = $r[1];
} else {
unless($selfref) {
$self->{accuracy} = $class -> accuracy();
$self->{precision} = $class -> precision();
}
}
return $self;
}
sub bpi {
# Class::method(...) -> Class->method(...)
unless (@_ && (defined(blessed($_[0])) && $_[0] -> isa(__PACKAGE__) ||
$_[0] =~ /^[a-z]\w*(?:::[a-z]\w*)*$/i))
{
#carp "Using ", (caller(0))[3], "() as a function is deprecated;",
# " use is as a method instead";
unshift @_, __PACKAGE__;
}
# Called as Argument list
# --------- -------------
# Math::BigFloat->bpi() ("Math::BigFloat")
# Math::BigFloat->bpi(10) ("Math::BigFloat", 10)
# $x->bpi() ($x)
# $x->bpi(10) ($x, 10)
# Math::BigFloat::bpi() ()
# Math::BigFloat::bpi(10) (10)
#
# In ambiguous cases, we favour the OO-style, so the following case
#
# $n = Math::BigFloat->new("10");
# $x = Math::BigFloat->bpi($n);
#
# which gives an argument list with the single element $n, is resolved as
#
# $n->bpi();
my $self = shift;
my $selfref = ref $self;
my $class = $selfref || $self;
my @r = @_; # rounding paramters
# Make "require" work.
$class -> import() if $IMPORT == 0;
if ($selfref) { # bpi() called as an instance method
return $self if $self -> modify('bpi');
} else { # bpi() called as a class method
$self = bless {}, $class; # initialize new instance
}
($self, @r) = $self -> _find_round_parameters(@r);
# The accuracy, i.e., the number of digits. Pi has one digit before the
# dot, so a precision of 4 digits is equivalent to an accuracy of 5 digits.
my $n = defined $r[0] ? $r[0]
: defined $r[1] ? 1 - $r[1]
: $self -> div_scale();
my $rmode = defined $r[2] ? $r[2] : $self -> round_mode();
my $pi;
if ($n <= 1000) {
# 75 x 14 = 1050 digits
my $all_digits = <<EOF;
314159265358979323846264338327950288419716939937510582097494459230781640628
620899862803482534211706798214808651328230664709384460955058223172535940812
848111745028410270193852110555964462294895493038196442881097566593344612847
564823378678316527120190914564856692346034861045432664821339360726024914127
372458700660631558817488152092096282925409171536436789259036001133053054882
046652138414695194151160943305727036575959195309218611738193261179310511854
807446237996274956735188575272489122793818301194912983367336244065664308602
139494639522473719070217986094370277053921717629317675238467481846766940513
200056812714526356082778577134275778960917363717872146844090122495343014654
958537105079227968925892354201995611212902196086403441815981362977477130996
051870721134999999837297804995105973173281609631859502445945534690830264252
230825334468503526193118817101000313783875288658753320838142061717766914730
359825349042875546873115956286388235378759375195778185778053217122680661300
192787661119590921642019893809525720106548586327886593615338182796823030195
EOF
# Should we round up?
my $round_up;
# From the string above, we need to extract the number of digits we
# want plus extra characters for the newlines.
my $nchrs = $n + int($n / 75);
# Extract the digits we want.
my $digits = substr($all_digits, 0, $nchrs);
# Find out whether we should round up or down. Rounding is easy, since
# pi is trancendental. With directed rounding, it doesn't matter what
# the following digits are. With rounding to nearest, we only have to
# look at one extra digit.
if ($rmode eq 'trunc') {
$round_up = 0;
} else {
my $next_digit = substr($all_digits, $nchrs, 1);
$round_up = $next_digit lt '5' ? 0 : 1;
}
# Remove the newlines.
$digits =~ tr/0-9//cd;
# Now do the rounding. We could easily make the regex substitution
# handle all cases, but we avoid using the regex engine when it is
# simple to avoid it.
if ($round_up) {
my $last_digit = substr($digits, -1, 1);
if ($last_digit lt '9') {
substr($digits, -1, 1) = ++$last_digit;
} else {
$digits =~ s{([0-8])(9+)$}
{ ($1 + 1) . ("0" x CORE::length($2)) }e;
}
}
# Convert to an object.
$pi = bless {
sign => '+',
_m => $LIB -> _new($digits),
_es => CORE::length($digits) > 1 ? '-' : '+',
_e => $LIB -> _new($n - 1),
}, $class;
} else {
# For large accuracy, the arctan formulas become very inefficient with
# Math::BigFloat, so use Brent-Salamin (aka AGM or Gauss-Legendre).
# Use a few more digits in the intermediate computations.
$n += 8;
$HALF = $class -> new($HALF) unless ref($HALF);
my ($an, $bn, $tn, $pn)
= ($class -> bone, $HALF -> copy() -> bsqrt($n),
$HALF -> copy() -> bmul($HALF), $class -> bone);
while ($pn < $n) {
my $prev_an = $an -> copy();
$an -> badd($bn) -> bmul($HALF, $n);
$bn -> bmul($prev_an) -> bsqrt($n);
$prev_an -> bsub($an);
$tn -> bsub($pn * $prev_an * $prev_an);
$pn -> badd($pn);
}
$an -> badd($bn);
$an -> bmul($an, $n) -> bdiv(4 * $tn, $n);
$an -> round(@r);
$pi = $an;
}
if (defined $r[0]) {
$pi -> accuracy($r[0]);
} elsif (defined $r[1]) {
$pi -> precision($r[1]);
}
$pi -> _dng() if ($pi -> is_int() ||
$pi -> is_inf() ||
$pi -> is_nan());
%$self = %$pi;
bless $self, ref($pi);
return $self;
}
sub copy {
my ($x, $class);
if (ref($_[0])) { # $y = $x -> copy()
$x = shift;
$class = ref($x);
} else { # $y = Math::BigInt -> copy($y)
$class = shift;
$x = shift;
}
carp "Rounding is not supported for ", (caller(0))[3], "()" if @_;
my $copy = bless {}, $class;
$copy->{sign} = $x->{sign};
$copy->{_es} = $x->{_es};
$copy->{_m} = $LIB->_copy($x->{_m});
$copy->{_e} = $LIB->_copy($x->{_e});
$copy->{accuracy} = $x->{accuracy} if exists $x->{accuracy};
$copy->{precision} = $x->{precision} if exists $x->{precision};
return $copy;
}
sub as_int {
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
# Temporarily disable upgrading and downgrading.
my $upg = Math::BigInt -> upgrade();
my $dng = Math::BigInt -> downgrade();
Math::BigInt -> upgrade(undef);
Math::BigInt -> downgrade(undef);
my $y;
if ($x -> isa("Math::BigInt")) {
$y = $x -> copy();
} else {
if ($x -> is_inf()) {
$y = Math::BigInt -> binf($x -> sign());
} elsif ($x -> is_nan()) {
$y = Math::BigInt -> bnan();
} else {
$y = Math::BigInt -> new($x -> copy() -> bint() -> bdstr());
}
# Copy the remaining instance variables.
($y->{accuracy}, $y->{precision}) = ($x->{accuracy}, $x->{precision});
}
$y -> round(@r);
# Restore upgrading and downgrading.
Math::BigInt -> upgrade($upg);
Math::BigInt -> downgrade($dng);
return $y;
}
sub as_rat {
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
# Temporarily disable upgrading and downgrading.
require Math::BigRat;
my $upg = Math::BigRat -> upgrade();
my $dng = Math::BigRat -> downgrade();
Math::BigRat -> upgrade(undef);
Math::BigRat -> downgrade(undef);
my $y;
if ($x -> isa("Math::BigRat")) {
$y = $x -> copy();
} else {
if ($x -> is_inf()) {
$y = Math::BigRat -> binf($x -> sign());
} elsif ($x -> is_nan()) {
$y = Math::BigRat -> bnan();
} else {
$y = Math::BigRat -> new($x -> bfstr());
}
# Copy the remaining instance variables.
($y->{accuracy}, $y->{precision}) = ($x->{accuracy}, $x->{precision});
}
$y -> round(@r);
# Restore upgrading and downgrading.
Math::BigRat -> upgrade($upg);
Math::BigRat -> downgrade($dng);
return $y;
}
sub as_float {
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
# Disable upgrading and downgrading.
require Math::BigFloat;
my $upg = Math::BigFloat -> upgrade();
my $dng = Math::BigFloat -> downgrade();
Math::BigFloat -> upgrade(undef);
Math::BigFloat -> downgrade(undef);
my $y;
if ($x -> isa("Math::BigFloat")) {
$y = $x -> copy();
} else {
if ($x -> is_inf()) {
$y = Math::BigFloat -> binf($x -> sign());
} elsif ($x -> is_nan()) {
$y = Math::BigFloat -> bnan();
} else {
if ($x -> isa("Math::BigRat")) {
if ($x -> is_int()) {
$y = Math::BigFloat -> new($x -> bdstr());
} else {
my ($num, $den) = $x -> fparts();
my $str = $num -> as_float() -> bdiv($den, @r) -> bdstr();
$y = Math::BigFloat -> new($str);
}
} else {
$y = Math::BigFloat -> new($x -> bdstr());
}
}
# Copy the remaining instance variables.
($y->{accuracy}, $y->{precision}) = ($x->{accuracy}, $x->{precision});
}
$y -> round(@r);
# Restore upgrading and downgrading.
Math::BigFloat -> upgrade($upg);
Math::BigFloat -> downgrade($dng);
return $y;
}
###############################################################################
# Boolean methods
###############################################################################
sub is_zero {
# return true if arg (BFLOAT or num_str) is zero
my (undef, $x) = ref($_[0]) ? (undef, @_) : objectify(1, @_);
return 0 if $x->{sign} ne '+';
return 1 if $LIB->_is_zero($x->{_m});
return 0;
}
sub is_one {
# return true if arg (BFLOAT or num_str) is +1 or -1 if signis given
my (undef, $x, $sign) = ref($_[0]) ? (undef, @_) : objectify(1, @_);
if (defined($sign)) {
croak 'is_one(): sign argument must be "+" or "-"'
unless $sign eq '+' || $sign eq '-';
} else {
$sign = '+';
}
return 0 if $x->{sign} ne $sign;
$LIB->_is_zero($x->{_e}) && $LIB->_is_one($x->{_m}) ? 1 : 0;
}
sub is_odd {
# return true if arg (BFLOAT or num_str) is odd or false if even
my (undef, $x) = ref($_[0]) ? (undef, @_) : objectify(1, @_);
return 0 unless $x -> is_finite();
$LIB->_is_zero($x->{_e}) && $LIB->_is_odd($x->{_m}) ? 1 : 0;
}
sub is_even {
# return true if arg (BINT or num_str) is even or false if odd
my (undef, $x) = ref($_[0]) ? (undef, @_) : objectify(1, @_);
return 0 unless $x -> is_finite();
($x->{_es} eq '+') && # 123.45 isn't
($LIB->_is_even($x->{_m})) ? 1 : 0; # but 1200 is
}
sub is_int {
# return true if arg (BFLOAT or num_str) is an integer
my (undef, $x) = ref($_[0]) ? (undef, @_) : objectify(1, @_);
return 0 unless $x -> is_finite();
return $x->{_es} eq '+' ? 1 : 0; # 1e-1 => no integer
}
###############################################################################
# Comparison methods
###############################################################################
sub bcmp {
# Compares 2 values. Returns one of undef, <0, =0, >0. (suitable for sort)
# set up parameters
my ($class, $x, $y, @r) = ref($_[0]) && ref($_[0]) eq ref($_[1])
? (ref($_[0]), @_)
: objectify(2, @_);
carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;
# Handle all 'nan' cases.
return if $x -> is_nan() || $y -> is_nan();
# Handle all '+inf' and '-inf' cases.
return 0 if ($x -> is_inf("+") && $y -> is_inf("+") ||
$x -> is_inf("-") && $y -> is_inf("-"));
return +1 if $x -> is_inf("+"); # x = +inf and y < +inf
return -1 if $x -> is_inf("-"); # x = -inf and y > -inf
return -1 if $y -> is_inf("+"); # x < +inf and y = +inf
return +1 if $y -> is_inf("-"); # x > -inf and y = -inf
# Handle all cases with opposite signs.
return +1 if $x->{sign} eq '+' && $y->{sign} eq '-'; # also does 0 <=> -y
return -1 if $x->{sign} eq '-' && $y->{sign} eq '+'; # also does -x <=> 0
# Handle all remaining zero cases.
my $xz = $x -> is_zero();
my $yz = $y -> is_zero();
return 0 if $xz && $yz; # 0 <=> 0
return -1 if $xz && $y->{sign} eq '+'; # 0 <=> +y
return +1 if $yz && $x->{sign} eq '+'; # +x <=> 0
# Both arguments are now finite, non-zero numbers with the same sign.
my $cmp;
# The next step is to compare the exponents, but since each mantissa is an
# integer of arbitrary value, the exponents must be normalized by the
# length of the mantissas before we can compare them.
my $mxl = $LIB->_len($x->{_m});
my $myl = $LIB->_len($y->{_m});
# If the mantissas have the same length, there is no point in normalizing
# the exponents by the length of the mantissas, so treat that as a special
# case.
if ($mxl == $myl) {
# First handle the two cases where the exponents have different signs.
if ($x->{_es} eq '+' && $y->{_es} eq '-') {
$cmp = +1;
} elsif ($x->{_es} eq '-' && $y->{_es} eq '+') {
$cmp = -1;
}
# Then handle the case where the exponents have the same sign.
else {
$cmp = $LIB->_acmp($x->{_e}, $y->{_e});
$cmp = -$cmp if $x->{_es} eq '-';
}
# Adjust for the sign, which is the same for x and y, and bail out if
# we're done.
$cmp = -$cmp if $x->{sign} eq '-'; # 124 > 123, but -124 < -123
return $cmp if $cmp;
}
# We must normalize each exponent by the length of the corresponding
# mantissa. Life is a lot easier if we first make both exponents
# non-negative. We do this by adding the same positive value to both
# exponent. This is safe, because when comparing the exponents, only the
# relative difference is important.
my $ex;
my $ey;
if ($x->{_es} eq '+') {
# If the exponent of x is >= 0 and the exponent of y is >= 0, there is
# no need to do anything special.
if ($y->{_es} eq '+') {
$ex = $LIB->_copy($x->{_e});
$ey = $LIB->_copy($y->{_e});
}
# If the exponent of x is >= 0 and the exponent of y is < 0, add the
# absolute value of the exponent of y to both.
else {
$ex = $LIB->_copy($x->{_e});
$ex = $LIB->_add($ex, $y->{_e}); # ex + |ey|
$ey = $LIB->_zero(); # -ex + |ey| = 0
}
} else {
# If the exponent of x is < 0 and the exponent of y is >= 0, add the
# absolute value of the exponent of x to both.
if ($y->{_es} eq '+') {
$ex = $LIB->_zero(); # -ex + |ex| = 0
$ey = $LIB->_copy($y->{_e});
$ey = $LIB->_add($ey, $x->{_e}); # ey + |ex|
}
# If the exponent of x is < 0 and the exponent of y is < 0, add the
# absolute values of both exponents to both exponents.
else {
$ex = $LIB->_copy($y->{_e}); # -ex + |ey| + |ex| = |ey|
$ey = $LIB->_copy($x->{_e}); # -ey + |ex| + |ey| = |ex|
}
}
# Now we can normalize the exponents by adding lengths of the mantissas.
$ex = $LIB->_add($ex, $LIB->_new($mxl));
$ey = $LIB->_add($ey, $LIB->_new($myl));
# We're done if the exponents are different.
$cmp = $LIB->_acmp($ex, $ey);
$cmp = -$cmp if $x->{sign} eq '-'; # 124 > 123, but -124 < -123
return $cmp if $cmp;
# Compare the mantissas, but first normalize them by padding the shorter
# mantissa with zeros (shift left) until it has the same length as the
# longer mantissa.
my $mx = $x->{_m};
my $my = $y->{_m};
if ($mxl > $myl) {
$my = $LIB->_lsft($LIB->_copy($my), $LIB->_new($mxl - $myl), 10);
} elsif ($mxl < $myl) {
$mx = $LIB->_lsft($LIB->_copy($mx), $LIB->_new($myl - $mxl), 10);
}
$cmp = $LIB->_acmp($mx, $my);
$cmp = -$cmp if $x->{sign} eq '-'; # 124 > 123, but -124 < -123
return $cmp;
}
sub bacmp {
# Compares 2 values, ignoring their signs.
# Returns one of undef, <0, =0, >0. (suitable for sort)
# set up parameters
my ($class, $x, $y, @r) = ref($_[0]) && ref($_[0]) eq ref($_[1])
? (ref($_[0]), @_)
: objectify(2, @_);
carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;
# handle +-inf and NaN
if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/) {
return if ($x -> is_nan() || $y -> is_nan());
return 0 if ($x -> is_inf() && $y -> is_inf());
return 1 if ($x -> is_inf() && !$y -> is_inf());
return -1;
}
# shortcut
my $xz = $x -> is_zero();
my $yz = $y -> is_zero();
return 0 if $xz && $yz; # 0 <=> 0
return -1 if $xz && !$yz; # 0 <=> +y
return 1 if $yz && !$xz; # +x <=> 0
# adjust so that exponents are equal
my $lxm = $LIB->_len($x->{_m});
my $lym = $LIB->_len($y->{_m});
my ($xes, $yes) = (1, 1);
$xes = -1 if $x->{_es} ne '+';
$yes = -1 if $y->{_es} ne '+';
# the numify somewhat limits our length, but makes it much faster
my $lx = $lxm + $xes * $LIB->_num($x->{_e});
my $ly = $lym + $yes * $LIB->_num($y->{_e});
my $l = $lx - $ly;
return $l <=> 0 if $l != 0;
# lengths (corrected by exponent) are equal
# so make mantissa equal-length by padding with zero (shift left)
my $diff = $lxm - $lym;
my $xm = $x->{_m}; # not yet copy it
my $ym = $y->{_m};
if ($diff > 0) {
$ym = $LIB->_copy($y->{_m});
$ym = $LIB->_lsft($ym, $LIB->_new($diff), 10);
} elsif ($diff < 0) {
$xm = $LIB->_copy($x->{_m});
$xm = $LIB->_lsft($xm, $LIB->_new(-$diff), 10);
}
$LIB->_acmp($xm, $ym);
}
###############################################################################
# Arithmetic methods
###############################################################################
sub bneg {
# (BINT or num_str) return BINT
# negate number or make a negated number from string
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
# Don't modify constant (read-only) objects.
return $x if $x -> modify('bneg');
# For +0 do not negate (to have always normalized +0).
$x->{sign} =~ tr/+-/-+/
unless $x->{sign} eq '+' && $LIB->_is_zero($x->{_m});
$x -> round(@r);
$x -> _dng() if ($x -> is_int() ||
$x -> is_inf() ||
$x -> is_nan());
return $x;
}
sub bnorm {
# bnorm() can't support rounding, because bround() and bfround() call
# bnorm(), which would recurse indefinitely.
# adjust m and e so that m is smallest possible
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;
# inf and nan
if ($x->{sign} !~ /^[+-]$/) {
$x -> round(@r);
$x -> _dng();
return $x;
}
my $zeros = $LIB->_zeros($x->{_m}); # correct for trailing zeros
if ($zeros != 0) {
my $z = $LIB->_new($zeros);
$x->{_m} = $LIB->_rsft($x->{_m}, $z, 10);
if ($x->{_es} eq '-') {
if ($LIB->_acmp($x->{_e}, $z) >= 0) {
$x->{_e} = $LIB->_sub($x->{_e}, $z);
$x->{_es} = '+' if $LIB->_is_zero($x->{_e});
} else {
$x->{_e} = $LIB->_sub($LIB->_copy($z), $x->{_e});
$x->{_es} = '+';
}
} else {
$x->{_e} = $LIB->_add($x->{_e}, $z);
}
} else {
# $x can only be 0Ey if there are no trailing zeros ('0' has 0 trailing
# zeros). So, for something like 0Ey, set y to 0, and -0 => +0
if ($LIB->_is_zero($x->{_m})) {
$x->{sign} = '+';
$x->{_es} = '+';
$x->{_e} = $LIB->_zero();
}
}
# Inf and NaN was handled above, so no need to check for this.
$x -> _dng() if $x -> is_int();
return $x;
}
sub binc {
# increment arg by one
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
# Don't modify constant (read-only) objects.
return $x if $x -> modify('binc');
# Inf and NaN
if ($x -> is_inf() || $x -> is_nan()) {
$x -> round(@r);
$x -> _dng();
return $x
}
# Non-integer
if ($x->{_es} eq '-') {
return $x -> badd($class -> bone(), @r);
}
# If the exponent is non-zero, convert the internal representation, so
# that, e.g., 12e+3 becomes 12000e+0 and we can easily increment the
# mantissa.
if (!$LIB->_is_zero($x->{_e})) {
$x->{_m} = $LIB->_lsft($x->{_m}, $x->{_e}, 10); # 1e2 => 100
$x->{_e} = $LIB->_zero(); # normalize
$x->{_es} = '+';
# we know that the last digit of $x will be '1' or '9', depending on
# the sign
}
# now $x->{_e} == 0
if ($x->{sign} eq '+') {
$x->{_m} = $LIB->_inc($x->{_m});
return $x -> bnorm() -> bround(@r);
} elsif ($x->{sign} eq '-') {
$x->{_m} = $LIB->_dec($x->{_m});
$x->{sign} = '+' if $LIB->_is_zero($x->{_m}); # -1 +1 => -0 => +0
return $x -> bnorm() -> bround(@r);
}
$x -> _dng() if ($x -> is_int() ||
$x -> is_inf() ||
$x -> is_nan());
return $x;
}
sub bdec {
# decrement arg by one
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
# Don't modify constant (read-only) objects.
return $x if $x -> modify('bdec');
# Inf and NaN
if ($x -> is_inf() || $x -> is_nan()) {
$x -> round(@r);
$x -> _dng();
return $x
}
# Non-integer
if ($x->{_es} eq '-') {
return $x -> badd($class -> bone('-'), @r);
}
# If the exponent is non-zero, convert the internal representation, so
# that, e.g., 12e+3 becomes 12000e+0 and we can easily increment the
# mantissa.
if (!$LIB->_is_zero($x->{_e})) {
$x->{_m} = $LIB->_lsft($x->{_m}, $x->{_e}, 10); # 1e2 => 100
$x->{_e} = $LIB->_zero(); # normalize
$x->{_es} = '+';
}
# now $x->{_e} == 0
my $zero = $x -> is_zero();
if (($x->{sign} eq '-') || $zero) { # x <= 0
$x->{_m} = $LIB->_inc($x->{_m});
$x->{sign} = '-' if $zero; # 0 => 1 => -1
$x->{sign} = '+' if $LIB->_is_zero($x->{_m}); # -1 +1 => -0 => +0
$x -> bnorm();
}
elsif ($x->{sign} eq '+') { # x > 0
$x->{_m} = $LIB->_dec($x->{_m});
$x -> bnorm();
}
$x -> round(@r);
$x -> _dng() if ($x -> is_int() ||
$x -> is_inf() ||
$x -> is_nan());
return $x;
}
sub badd {
# set up parameters
my ($class, $x, $y, @r) = ref($_[0]) && ref($_[0]) eq ref($_[1])
? (ref($_[0]), @_)
: objectify(2, @_);
# Don't modify constant (read-only) objects.
return $x if $x -> modify('badd');
unless ($x -> is_finite() && $y -> is_finite()) {
return $x -> bnan(@r) if $x -> is_nan() || $y -> is_nan();
return $x -> is_inf("+") ? ($y -> is_inf("-") ? $x -> bnan(@r)
: $x -> binf("+", @r))
: $x -> is_inf("-") ? ($y -> is_inf("+") ? $x -> bnan(@r)
: $x -> binf("-", @r))
: ($y -> is_inf("+") ? $x -> binf("+", @r)
: $x -> binf("-", @r));
}
return $x -> _upg() -> badd($y, @r) if $class -> upgrade();
$r[3] = $y; # no push!
# for speed: no add for $x + 0
if ($y -> is_zero()) {
$x -> round(@r);
}
# for speed: no add for 0 + $y
elsif ($x -> is_zero()) {
# make copy, clobbering up x (modify in place!)
$x->{_e} = $LIB->_copy($y->{_e});
$x->{_es} = $y->{_es};
$x->{_m} = $LIB->_copy($y->{_m});
$x->{sign} = $y->{sign} || $nan;
$x -> round(@r);
}
# both $x and $y are non-zero
else {
# take lower of the two e's and adapt m1 to it to match m2
my $e = $y->{_e};
$e = $LIB->_zero() if !defined $e; # if no BFLOAT?
$e = $LIB->_copy($e); # make copy (didn't do it yet)
my $es;
($e, $es) = $LIB -> _ssub($e, $y->{_es} || '+', $x->{_e}, $x->{_es});
my $add = $LIB->_copy($y->{_m});
if ($es eq '-') { # < 0
$x->{_m} = $LIB->_lsft($x->{_m}, $e, 10);
($x->{_e}, $x->{_es}) = $LIB -> _sadd($x->{_e}, $x->{_es}, $e, $es);
} elsif (!$LIB->_is_zero($e)) { # > 0
$add = $LIB->_lsft($add, $e, 10);
}
# else: both e are the same, so just leave them
if ($x->{sign} eq $y->{sign}) {
$x->{_m} = $LIB->_add($x->{_m}, $add);
} else {
($x->{_m}, $x->{sign}) =
$LIB -> _sadd($x->{_m}, $x->{sign}, $add, $y->{sign});
}
# delete trailing zeros, then round
$x -> bnorm() -> round(@r);
}
$x -> _dng() if ($x -> is_int() ||
$x -> is_inf() ||
$x -> is_nan());
return $x;
}
sub bsub {
# set up parameters
my ($class, $x, $y, @r) = ref($_[0]) && ref($_[0]) eq ref($_[1])
? (ref($_[0]), @_)
: objectify(2, @_);
# Don't modify constant (read-only) objects.
return $x if $x -> modify('bsub');
$r[3] = $y; # no push!
unless ($x -> is_finite() && $y -> is_finite()) {
return $x -> bnan(@r) if $x -> is_nan() || $y -> is_nan();
return $x -> is_inf("+") ? ($y -> is_inf("+") ? $x -> bnan(@r)
: $x -> binf("+", @r))
: $x -> is_inf("-") ? ($y -> is_inf("-") ? $x -> bnan(@r)
: $x -> binf("-", @r))
: ($y -> is_inf("+") ? $x -> binf("-", @r)
: $x -> binf("+", @r));
}
$x -> badd($y -> copy() -> bneg(), @r);
return $x;
}
sub bmul {
# multiply two numbers
# set up parameters
my ($class, $x, $y, @r) = ref($_[0]) && ref($_[0]) eq ref($_[1])
? (ref($_[0]), @_)
: objectify(2, @_);
# Don't modify constant (read-only) objects.
return $x if $x -> modify('bmul');
return $x -> bnan(@r) if $x -> is_nan() || $y -> is_nan();
# inf handling
if (($x->{sign} =~ /^[+-]inf$/) || ($y->{sign} =~ /^[+-]inf$/)) {
return $x -> bnan(@r) if $x -> is_zero() || $y -> is_zero();
# result will always be +-inf:
# +inf * +/+inf => +inf, -inf * -/-inf => +inf
# +inf * -/-inf => -inf, -inf * +/+inf => -inf
return $x -> binf(@r) if ($x->{sign} =~ /^\+/ && $y->{sign} =~ /^\+/);
return $x -> binf(@r) if ($x->{sign} =~ /^-/ && $y->{sign} =~ /^-/);
return $x -> binf('-', @r);
}
return $x -> _upg() -> bmul($y, @r) if $class -> upgrade();
# aEb * cEd = (a*c)E(b+d)
$x->{_m} = $LIB->_mul($x->{_m}, $y->{_m});
($x->{_e}, $x->{_es})
= $LIB -> _sadd($x->{_e}, $x->{_es}, $y->{_e}, $y->{_es});
$r[3] = $y; # no push!
# adjust sign:
$x->{sign} = $x->{sign} ne $y->{sign} ? '-' : '+';
$x -> bnorm -> round(@r);
$x -> _dng() if ($x -> is_int() ||
$x -> is_inf() ||
$x -> is_nan());
return $x;
}
*bdiv = \&bfdiv;
*bmod = \&bfmod;
sub bfdiv {
# This does floored division (or floor division) where the quotient is
# rounded towards minus infinity.
#
# ($q, $r) = $x -> btdiv($y) returns $q and $r so that $q is floor($x / $y)
# and $q * $y + $r = $x.
# Set up parameters.
my ($class, $x, $y, @r) = ref($_[0]) && ref($_[0]) eq ref($_[1])
? (ref($_[0]), @_)
: objectify(2, @_);
###########################################################################
# Code for all classes that share the common interface.
###########################################################################
# Don't modify constant (read-only) objects.
return $x if $x -> modify('bfdiv');
my $wantarray = wantarray; # call only once
# At least one argument is NaN. This is handled the same way as in
# Math::BigInt -> bdiv(). See the comment in the code for Math::BigInt ->
# bdiv() for further details.
if ($x -> is_nan() || $y -> is_nan()) {
return $wantarray ? ($x -> bnan(@r), $class -> bnan(@r))
: $x -> bnan(@r);
}
# Divide by zero and modulo zero. This is handled the same way as in
# Math::BigInt -> bdiv(). See the comment in the code for Math::BigInt ->
# bdiv() for further details.
if ($y -> is_zero()) {
my $rem;
if ($wantarray) {
$rem = $x -> copy() -> round(@r);
$rem -> _dng() if $rem -> is_int();
}
if ($x -> is_zero()) {
$x -> bnan(@r);
} else {
$x -> binf($x->{sign}, @r);
}
return $wantarray ? ($x, $rem) : $x;
}
# Numerator (dividend) is +/-inf. This is handled the same way as in
# Math::BigInt -> bdiv(). See the comment in the code for Math::BigInt ->
# bdiv() for further details.
if ($x -> is_inf()) {
my $rem;
$rem = $class -> bnan(@r) if $wantarray;
if ($y -> is_inf()) {
$x -> bnan(@r);
} else {
my $sign = $x -> bcmp(0) == $y -> bcmp(0) ? '+' : '-';
$x -> binf($sign, @r);
}
return $wantarray ? ($x, $rem) : $x;
}
# Denominator (divisor) is +/-inf. This is handled the same way as in
# Math::BigInt -> bdiv(), with one exception: In scalar context,
# Math::BigFloat does true division (although rounded), not floored
# division (F-division), so a finite number divided by +/-inf is always
# zero. See the comment in the code for Math::BigInt -> bdiv() for further
# details.
if ($y -> is_inf()) {
my $rem;
if ($wantarray) {
if ($x -> is_zero() || $x -> bcmp(0) == $y -> bcmp(0)) {
$rem = $x -> copy() -> round(@r);
$rem -> _dng() if $rem -> is_int();
$x -> bzero(@r);
} else {
$rem = $class -> binf($y -> {sign}, @r);
$x -> bone('-', @r);
}
} else {
$x -> bzero(@r);
}
return $wantarray ? ($x, $rem) : $x;
}
# At this point, both the numerator and denominator are finite, non-zero
# numbers.
# we need to limit the accuracy to protect against overflow
my $fallback = 0;
my (@params, $scale);
($x, @params) = $x->_find_round_parameters($r[0], $r[1], $r[2], $y);
if ($x -> is_nan()) { # error in _find_round_parameters?
$x -> round(@r);
return $wantarray ? ($x, $class -> bnan(@r)) : $x;
}
# no rounding at all, so must use fallback
if (scalar @params == 0) {
# simulate old behaviour
$params[0] = $class -> div_scale(); # and round to it as accuracy
$scale = $params[0]+4; # at least four more for proper round
$params[2] = $r[2]; # round mode by caller or undef
$fallback = 1; # to clear a/p afterwards
} else {
# the 4 below is empirical, and there might be cases where it is not
# enough...
$scale = abs($params[0] || $params[1]) + 4; # take whatever is defined
}
# Temporarily disable downgrading
my $dng = Math::BigFloat -> downgrade();
Math::BigFloat -> downgrade(undef);
my $rem;
$rem = $class -> bzero() if $wantarray;
$y = $class -> new($y) unless $y -> isa('Math::BigFloat');
my $lx = $LIB -> _len($x->{_m});
my $ly = $LIB -> _len($y->{_m});
$scale = $lx if $lx > $scale;
$scale = $ly if $ly > $scale;
my $diff = $ly - $lx;
$scale += $diff if $diff > 0; # if lx << ly, but not if ly << lx!
# Are both operands the same object, i.e., like $x -> bdiv($x)? If so,
# flipping the sign of $y also flips the sign of $x.
my $xsign = $x -> {sign};
my $ysign = $y -> {sign};
$y -> {sign} =~ tr/+-/-+/; # Flip the sign of $y, and see ...
my $same = $xsign ne $x -> {sign}; # ... if that changed the sign of $x.
$y -> {sign} = $ysign; # Re-insert the original sign.
if ($same) { # $x -> bdiv($x)
$x -> bone();
} else {
# make copy of $x in case of list context for later remainder
# calculation
$rem = $x -> copy() if $wantarray;
$x->{sign} = $x->{sign} ne $y->{sign} ? '-' : '+';
# promote Math::BigInt and its subclasses (except when already a
# Math::BigFloat)
$y = $class -> new($y) unless $y -> isa('Math::BigFloat');
# calculate the result to $scale digits and then round it
# (a * 10 ** b) / (c * 10 ** d) => (a/c) * 10 ** (b-d)
$x->{_m} = $LIB->_lsft($x->{_m}, $LIB->_new($scale), 10); # scale up
$x->{_m} = $LIB->_div($x->{_m}, $y->{_m}); # divide
# correct exponent of $x
($x->{_e}, $x->{_es})
= $LIB -> _ssub($x->{_e}, $x->{_es}, $y->{_e}, $y->{_es});
# correct for 10**scale
($x->{_e}, $x->{_es})
= $LIB -> _ssub($x->{_e}, $x->{_es}, $LIB->_new($scale), '+');
$x -> bnorm(); # remove trailing zeros
}
# shortcut to not run through _find_round_parameters again
if (defined $params[0]) {
$x->{accuracy} = undef; # clear before round
$x -> bround($params[0], $params[2]); # then round accordingly
} else {
$x->{precision} = undef; # clear before round
$x -> bfround($params[1], $params[2]); # then round accordingly
}
if ($fallback) {
# clear a/p after round, since user did not request it
$x->{accuracy} = undef;
$x->{precision} = undef;
}
# Restore downgrading
Math::BigFloat -> downgrade($dng);
if ($wantarray) {
$x -> bfloor();
$rem -> bfmod($y, @params); # copy already done
if ($fallback) {
# clear a/p after round, since user did not request it
$rem->{accuracy} = undef;
$rem->{precision} = undef;
}
$x -> _dng() if $x -> is_int();
$rem -> _dng() if $rem -> is_int();
return $x, $rem;
}
$x -> _dng() if $x -> is_int();
$x; # rounding already done above
}
sub bfmod {
# (dividend: BFLOAT or num_str, divisor: BFLOAT or num_str) return
# remainder
# set up parameters
my ($class, $x, $y, @r) = ref($_[0]) && ref($_[0]) eq ref($_[1])
? (ref($_[0]), @_)
: objectify(2, @_);
# Don't modify constant (read-only) objects.
return $x if $x -> modify('bfmod');
# At least one argument is NaN. This is handled the same way as in
# Math::BigInt -> bfmod().
return $x -> bnan(@r) if $x -> is_nan() || $y -> is_nan();
# Modulo zero. This is handled the same way as in Math::BigInt -> bfmod().
if ($y -> is_zero()) {
return $x -> round(@r);
}
# Numerator (dividend) is +/-inf. This is handled the same way as in
# Math::BigInt -> bfmod().
if ($x -> is_inf()) {
return $x -> bnan(@r);
}
# Denominator (divisor) is +/-inf. This is handled the same way as in
# Math::BigInt -> bfmod().
if ($y -> is_inf()) {
if ($x -> is_zero() || $x -> bcmp(0) == $y -> bcmp(0)) {
return $x -> round(@r);
} else {
return $x -> binf($y -> sign(), @r);
}
}
# Modulo is zero if $x is zero or if $x is an integer and $y is +/-1.
return $x -> bzero(@r) if $x -> is_zero()
|| ($x -> is_int() &&
# check that $y == +1 or $y == -1:
($LIB->_is_zero($y->{_e}) && $LIB->_is_one($y->{_m})));
# Numerator (dividend) and denominator (divisor) are identical. Return
# zero.
my $cmp = $x -> bacmp($y); # $x <=> $y
if ($cmp == 0) { # $x == $y => result 0
return $x -> bzero(@r);
}
# Compare the exponents of $x and $y.
my $ecmp = $LIB->_scmp($x->{_e}, $x->{_es}, $y->{_e}, $y->{_es});
my $ym = $y->{_m}; # mantissa of y, scaled if necessary
if ($ecmp > 0) {
# $x has a larger exponent than $y, so shift the mantissa of $x by the
# difference between the exponents of $x and $y.
#
# 123e+2 % 456e+1 => 1230 % 456 (+2 - +1 = 1)
# 123e+2 % 456e-1 => 123000 % 456 (+2 - -1 = 3)
# 456e-1 % 123e-3 => 12300 % 456 (-1 - -3 = 2)
# get the difference between exponents; $ds is always "+" here
my ($de, $ds) = $LIB->_ssub($LIB->_copy($x->{_e}), $x->{_es},
$y->{_e}, $y->{_es});
# adjust the mantissa of x by the difference between exponents
$x->{_m} = $LIB->_lsft($x->{_m}, $de, 10);
# compute the modulus
$x->{_m} = $LIB->_mod($x->{_m}, $ym);
# adjust the exponent of x to correct for the ajustment of the mantissa
($x->{_e}, $x->{_es}) = $LIB->_ssub($x->{_e}, $x->{_es}, $de, $ds);
} elsif ($ecmp < 0) {
# $x has a smaller exponent than $y, so shift the mantissa of $y by the
# difference between the exponents of $x and $y.
#
# 123456e+1 % 78e+2 => 123456 % 780 (+2 - +1 = 1)
# 123456e-2 % 78e+1 => 123456 % 78000 (+1 - -2 = 3)
# get the difference between exponents; $ds is always "+" here
my ($de, $ds) = $LIB->_ssub($LIB->_copy($y->{_e}), $y->{_es},
$x->{_e}, $x->{_es});
# adjust the mantissa of y by the difference between exponents
$ym = $LIB->_lsft($LIB->_copy($ym), $de, 10);
# compute the modulus
$x->{_m} = $LIB->_mod($x->{_m}, $ym);
} else {
# $x has the same exponent as $y, so compute the modulus directly
# compute the modulus
$x->{_m} = $LIB->_mod($x->{_m}, $ym);
}
if ($LIB->_is_zero($x->{_m})) {
$x->{sign} = '+';
} else {
# adjust for floored division/modulus
$x->{_m} = $LIB->_sub($ym, $x->{_m}, 1)
if $x->{sign} ne $y->{sign};
$x->{sign} = $y->{sign};
}
$x -> bnorm();
$x -> round($r[0], $r[1], $r[2], $y);
$x -> _dng() if $x -> is_int();
return $x;
}
sub btdiv {
# This does truncated division, where the quotient is truncted, i.e.,
# rounded towards zero.
#
# ($q, $r) = $x -> btdiv($y) returns $q and $r so that $q is int($x / $y)
# and $q * $y + $r = $x.
# Set up parameters
my ($class, $x, $y, @r) = ref($_[0]) && ref($_[0]) eq ref($_[1])
? (ref($_[0]), @_)
: objectify(2, @_);
###########################################################################
# Code for all classes that share the common interface.
###########################################################################
# Don't modify constant (read-only) objects.
return $x if $x -> modify('btdiv');
my $wantarray = wantarray; # call only once
# At least one argument is NaN. Return NaN for both quotient and the
# modulo/remainder.
if ($x -> is_nan() || $y -> is_nan()) {
return $wantarray ? ($x -> bnan(@r), $class -> bnan(@r))
: $x -> bnan(@r);
}
# Divide by zero and modulo zero.
#
# Division: Use the common convention that x / 0 is inf with the same sign
# as x, except when x = 0, where we return NaN. This is also what earlier
# versions did.
#
# Modulo: In modular arithmetic, the congruence relation z = x (mod y)
# means that there is some integer k such that z - x = k y. If y = 0, we
# get z - x = 0 or z = x. This is also what earlier versions did, except
# that 0 % 0 returned NaN.
#
# inf / 0 = inf inf % 0 = inf
# 5 / 0 = inf 5 % 0 = 5
# 0 / 0 = NaN 0 % 0 = 0
# -5 / 0 = -inf -5 % 0 = -5
# -inf / 0 = -inf -inf % 0 = -inf
if ($y -> is_zero()) {
my $rem;
if ($wantarray) {
$rem = $x -> copy(@r);
}
if ($x -> is_zero()) {
$x -> bnan(@r);
} else {
$x -> binf($x -> {sign}, @r);
}
return $wantarray ? ($x, $rem) : $x;
}
# Numerator (dividend) is +/-inf, and denominator is finite and non-zero.
# The divide by zero cases are covered above. In all of the cases listed
# below we return the same as core Perl.
#
# inf / -inf = NaN inf % -inf = NaN
# inf / -5 = -inf inf % -5 = NaN
# inf / 5 = inf inf % 5 = NaN
# inf / inf = NaN inf % inf = NaN
#
# -inf / -inf = NaN -inf % -inf = NaN
# -inf / -5 = inf -inf % -5 = NaN
# -inf / 5 = -inf -inf % 5 = NaN
# -inf / inf = NaN -inf % inf = NaN
if ($x -> is_inf()) {
my $rem;
$rem = $class -> bnan(@r) if $wantarray;
if ($y -> is_inf()) {
$x -> bnan(@r);
} else {
my $sign = $x -> bcmp(0) == $y -> bcmp(0) ? '+' : '-';
$x -> binf($sign,@r );
}
return $wantarray ? ($x, $rem) : $x;
}
# Denominator (divisor) is +/-inf. The cases when the numerator is +/-inf
# are covered above. In the modulo cases (in the right column) we return
# the same as core Perl, which does floored division, so for consistency we
# also do floored division in the division cases (in the left column).
#
# -5 / inf = 0 -5 % inf = -5
# 0 / inf = 0 0 % inf = 0
# 5 / inf = 0 5 % inf = 5
#
# -5 / -inf = 0 -5 % -inf = -5
# 0 / -inf = 0 0 % -inf = 0
# 5 / -inf = 0 5 % -inf = 5
if ($y -> is_inf()) {
my $rem;
if ($wantarray) {
$rem = $x -> copy() -> round(@r);
$rem -> _dng() if $rem -> is_int();
}
$x -> bzero(@r);
return $wantarray ? ($x, $rem) : $x;
}
# At this point, both the numerator and denominator are finite, non-zero
# numbers.
# we need to limit the accuracy to protect against overflow
my $fallback = 0;
my (@params, $scale);
($x, @params) = $x->_find_round_parameters($r[0], $r[1], $r[2], $y);
if ($x -> is_nan()) { # error in _find_round_parameters?
$x -> round(@r);
return $wantarray ? ($x, $class -> bnan(@r)) : $x;
}
# no rounding at all, so must use fallback
if (scalar @params == 0) {
# simulate old behaviour
$params[0] = $class -> div_scale(); # and round to it as accuracy
$scale = $params[0]+4; # at least four more for proper round
$params[2] = $r[2]; # round mode by caller or undef
$fallback = 1; # to clear a/p afterwards
} else {
# the 4 below is empirical, and there might be cases where it is not
# enough...
$scale = abs($params[0] || $params[1]) + 4; # take whatever is defined
}
# Temporarily disable downgrading
my $dng = Math::BigFloat -> downgrade();
Math::BigFloat -> downgrade(undef);
my $rem;
$rem = $class -> bzero() if $wantarray;
$y = $class -> new($y) unless $y -> isa('Math::BigFloat');
my $lx = $LIB -> _len($x->{_m});
my $ly = $LIB -> _len($y->{_m});
$scale = $lx if $lx > $scale;
$scale = $ly if $ly > $scale;
my $diff = $ly - $lx;
$scale += $diff if $diff > 0; # if lx << ly, but not if ly << lx!
# Are both operands the same object, i.e., like $x -> bdiv($x)? If so,
# flipping the sign of $y also flips the sign of $x.
my $xsign = $x -> {sign};
my $ysign = $y -> {sign};
$y -> {sign} =~ tr/+-/-+/; # Flip the sign of $y, and see ...
my $same = $xsign ne $x -> {sign}; # ... if that changed the sign of $x.
$y -> {sign} = $ysign; # Re-insert the original sign.
if ($same) { # $x -> bdiv($x)
$x -> bone();
} else {
# make copy of $x in case of list context for later remainder
# calculation
$rem = $x -> copy() if $wantarray;
$x->{sign} = $x->{sign} ne $y->{sign} ? '-' : '+';
# promote Math::BigInt and its subclasses (except when already a
# Math::BigFloat)
$y = $class -> new($y) unless $y -> isa('Math::BigFloat');
# calculate the result to $scale digits and then round it
# (a * 10 ** b) / (c * 10 ** d) => (a/c) * 10 ** (b-d)
$x->{_m} = $LIB->_lsft($x->{_m}, $LIB->_new($scale), 10); # scale up
$x->{_m} = $LIB->_div($x->{_m}, $y->{_m}); # divide
# correct exponent of $x
($x->{_e}, $x->{_es})
= $LIB -> _ssub($x->{_e}, $x->{_es}, $y->{_e}, $y->{_es});
# correct for 10**scale
($x->{_e}, $x->{_es})
= $LIB -> _ssub($x->{_e}, $x->{_es}, $LIB->_new($scale), '+');
$x -> bnorm(); # remove trailing zeros in mantissa
}
# shortcut to not run through _find_round_parameters again
if (defined $params[0]) {
$x->{accuracy} = undef; # clear before round
$x -> bround($params[0], $params[2]); # then round accordingly
} else {
$x->{precision} = undef; # clear before round
$x -> bfround($params[1], $params[2]); # then round accordingly
}
if ($fallback) {
# clear a/p after round, since user did not request it
$x->{accuracy} = undef;
$x->{precision} = undef;
}
# Restore downgrading
Math::BigFloat -> downgrade($dng);
if ($wantarray) {
$x -> bint();
$rem -> btmod($y, @params); # copy already done
if ($fallback) {
# clear a/p after round, since user did not request it
$rem->{accuracy} = undef;
$rem->{precision} = undef;
}
$x -> _dng() if $x -> is_int();
$rem -> _dng() if $rem -> is_int();
return $x, $rem;
}
$x -> _dng() if $x -> is_int();
$x; # rounding already done above
}
sub btmod {
# (dividend: BFLOAT or num_str, divisor: BFLOAT or num_str) return
# remainder
# set up parameters
my ($class, $x, $y, @r) = ref($_[0]) && ref($_[0]) eq ref($_[1])
? (ref($_[0]), @_)
: objectify(2, @_);
# Don't modify constant (read-only) objects.
return $x if $x -> modify('btmod');
# At least one argument is NaN. This is handled the same way as in
# Math::BigInt -> btmod().
return $x -> bnan(@r) if $x -> is_nan() || $y -> is_nan();
# Modulo zero. This is handled the same way as in Math::BigInt -> btmod().
if ($y -> is_zero()) {
return $x -> round(@r);
}
# Numerator (dividend) is +/-inf. This is handled the same way as in
# Math::BigInt -> btmod().
if ($x -> is_inf()) {
return $x -> bnan(@r);
}
# Denominator (divisor) is +/-inf. This is handled the same way as in
# Math::BigInt -> btmod().
if ($y -> is_inf()) {
return $x -> round(@r);
}
# Modulo is zero if $x is zero or if $x is an integer and $y is +/-1.
return $x -> bzero(@r) if $x -> is_zero()
|| ($x -> is_int() &&
# check that $y == +1 or $y == -1:
($LIB->_is_zero($y->{_e}) && $LIB->_is_one($y->{_m})));
# Numerator (dividend) and denominator (divisor) are identical. Return
# zero.
my $cmp = $x -> bacmp($y); # $x <=> $y
if ($cmp == 0) { # $x == $y => result 0
return $x -> bzero(@r);
}
# Compare the exponents of $x and $y.
my $ecmp = $LIB->_scmp($x->{_e}, $x->{_es}, $y->{_e}, $y->{_es});
if ($ecmp > 0) {
# $x has a larger exponent than $y, so shift the mantissa of $x by the
# difference between the exponents of $x and $y.
#
# 123e+2 % 456e+1 => 1230 % 456 (+2 - +1 = 1)
# 123e+2 % 456e-1 => 123000 % 456 (+2 - -1 = 3)
# 456e-1 % 123e-3 => 12300 % 456 (-1 - -3 = 2)
# get the difference between exponents; $ds is always "+" here
my ($de, $ds) = $LIB->_ssub($LIB->_copy($x->{_e}), $x->{_es},
$y->{_e}, $y->{_es});
# adjust the mantissa of x by the difference between exponents
$x->{_m} = $LIB->_lsft($x->{_m}, $de, 10);
# compute the modulus
$x->{_m} = $LIB->_mod($x->{_m}, $y->{_m});
# adjust the exponent of x to correct for the ajustment of the mantissa
($x->{_e}, $x->{_es}) = $LIB->_ssub($x->{_e}, $x->{_es}, $de, $ds);
} elsif ($ecmp < 0) {
# $x has a smaller exponent than $y, so shift the mantissa of $y by the
# difference between the exponents of $x and $y.
#
# 123456e+1 % 78e+2 => 123456 % 780 (+2 - +1 = 1)
# 123456e-2 % 78e+1 => 123456 % 78000 (+1 - -2 = 3)
# get the difference between exponents; $ds is always "+" here
my ($de, $ds) = $LIB->_ssub($LIB->_copy($y->{_e}), $y->{_es},
$x->{_e}, $x->{_es});
# adjust the mantissa of y by the difference between exponents
my $ym = $LIB->_lsft($LIB->_copy($y->{_m}), $de, 10);
# compute the modulus
$x->{_m} = $LIB->_mod($x->{_m}, $ym);
} else {
# $x has the same exponent as $y, so compute the modulus directly
# compute the modulus
$x->{_m} = $LIB->_mod($x->{_m}, $y->{_m});
}
$x->{sign} = '+' if $LIB->_is_zero($x->{_m}); # fix sign for -0
$x -> bnorm();
$x -> round($r[0], $r[1], $r[2], $y);
$x -> _dng() if $x -> is_int();
return $x;
}
sub binv {
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
# Don't modify constant (read-only) objects.
return $x if $x -> modify('binv');
# bone() might perform downgrading, so temporarily disable downgrading
my $dng = Math::BigFloat -> downgrade();
Math::BigFloat -> downgrade(undef);
my $inv = $class -> bone() -> bdiv($x, @r);
# Restore downgrading
Math::BigFloat -> downgrade($dng);
%$x = %$inv;
$x -> round(@r);
$x -> _dng() if ($x -> is_int() ||
$x -> is_inf() ||
$x -> is_nan());
return $x;
}
sub bsqrt {
# calculate square root
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
# Don't modify constant (read-only) objects.
return $x if $x -> modify('bsqrt');
# Handle trivial cases.
return $x -> bnan(@r) if $x -> is_nan();
return $x -> binf("+", @r) if $x -> is_inf("+");
return $x -> round(@r) if $x -> is_zero() || $x -> is_one();
# We don't support complex numbers.
if ($x -> is_neg()) {
return $x -> _upg() -> bsqrt(@r) if $class -> upgrade();
return $x -> bnan(@r);
}
# we need to limit the accuracy to protect against overflow
my $fallback = 0;
my (@params, $scale);
($x, @params) = $x->_find_round_parameters(@r);
# error in _find_round_parameters?
return $x -> bnan(@r) if $x -> is_nan();
# no rounding at all, so must use fallback
if (scalar @params == 0) {
# simulate old behaviour
$params[0] = $class -> div_scale(); # and round to it as accuracy
$scale = $params[0]+4; # at least four more for proper round
$params[2] = $r[2]; # round mode by caller or undef
$fallback = 1; # to clear a/p afterwards
} else {
# the 4 below is empirical, and there might be cases where it is not
# enough...
$scale = abs($params[0] || $params[1]) + 4; # take whatever is defined
}
# Shift the significand left or right to get the desired number of digits,
# which is 2*$scale with possibly one extra digit to ensure that the
# exponent is an even number.
my $l = $LIB -> _len($x->{_m});
my $n = 2 * $scale - $l; # how much should we shift?
$n++ if ($l % 2 xor $LIB -> _is_odd($x->{_e}));
my ($na, $ns) = $n < 0 ? (abs($n), "-") : ($n, "+");
$na = $LIB -> _new($na);
$x->{_m} = $ns eq "+" ? $LIB -> _lsft($x->{_m}, $na, 10)
: $LIB -> _rsft($x->{_m}, $na, 10);
$x->{_m} = $LIB -> _sqrt($x->{_m});
# Adjust the exponent by the amount that we shifted the significand. The
# square root of the exponent is simply half of it: sqrt(10^(2*a)) = 10^a.
($x->{_e}, $x->{_es}) = $LIB -> _ssub($x->{_e}, $x->{_es}, $na, $ns);
$x->{_e} = $LIB -> _div($x->{_e}, $LIB -> _new("2"));
# Normalize to get rid of any trailing zeros in the significand.
$x -> bnorm();
# shortcut to not run through _find_round_parameters again
if (defined $params[0]) {
$x -> bround($params[0], $params[2]); # then round accordingly
} else {
$x -> bfround($params[1], $params[2]); # then round accordingly
}
if ($fallback) {
# clear a/p after round, since user did not request it
$x->{accuracy} = undef;
$x->{precision} = undef;
}
$x -> round(@r);
$x -> _dng() if $x -> is_int();
$x;
}
sub bpow {
# (BFLOAT or num_str, BFLOAT or num_str) return BFLOAT
# compute power of two numbers, second arg is used as integer
# modifies first argument
# set up parameters
my ($class, $x, $y, $a, $p, $r) = (ref($_[0]), @_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
($class, $x, $y, $a, $p, $r) = objectify(2, @_);
}
# Don't modify constant (read-only) objects.
return $x if $x -> modify('bpow');
# $x and/or $y is a NaN
return $x -> bnan() if $x -> is_nan() || $y -> is_nan();
# $x and/or $y is a +/-Inf
if ($x -> is_inf("-")) {
return $x -> bzero() if $y -> is_negative();
return $x -> bnan() if $y -> is_zero();
return $x if $y -> is_odd();
return $x -> bneg();
} elsif ($x -> is_inf("+")) {
return $x -> bzero() if $y -> is_negative();
return $x -> bnan() if $y -> is_zero();
return $x;
} elsif ($y -> is_inf("-")) {
return $x -> bnan() if $x -> is_one("-");
return $x -> binf("+") if $x > -1 && $x < 1;
return $x -> bone() if $x -> is_one("+");
return $x -> bzero();
} elsif ($y -> is_inf("+")) {
return $x -> bnan() if $x -> is_one("-");
return $x -> bzero() if $x > -1 && $x < 1;
return $x -> bone() if $x -> is_one("+");
return $x -> binf("+");
}
if ($x -> is_zero()) {
return $x -> bone() if $y -> is_zero();
return $x -> binf() if $y -> is_negative();
return $x;
}
# We don't support complex numbers, so upgrade or return NaN.
if ($x -> is_negative() && !$y -> is_int()) {
return $x -> _upg() -> bpow($y, $a, $p, $r) if $class -> upgrade();
return $x -> bnan();
}
if ($x -> is_one("+") || $y -> is_one()) {
return $x;
}
if ($x -> is_one("-")) {
return $x if $y -> is_odd();
return $x -> bneg();
}
return $x -> _pow($y, $a, $p, $r) if !$y -> is_int();
# We should NOT be looking at private variables of other objects. Fixme XXX
my $y1 = $y -> as_int()->{value}; # make MBI part
my $new_sign = '+';
$new_sign = $LIB -> _is_odd($y1) ? '-' : '+' if $x->{sign} ne '+';
# calculate $x->{_m} ** $y and $x->{_e} * $y separately (faster)
$x->{_m} = $LIB -> _pow($x->{_m}, $y1);
$x->{_e} = $LIB -> _mul($x->{_e}, $y1);
$x->{sign} = $new_sign;
$x -> bnorm();
# x ** (-y) = 1 / (x ** y)
if ($y->{sign} eq '-') {
# modify $x in place!
my $z = $x -> copy();
$x -> bone();
# round in one go (might ignore y's A!)
return scalar $x -> bdiv($z, $a, $p, $r);
}
$x -> round($a, $p, $r, $y);
$x -> _dng() if ($x -> is_int() ||
$x -> is_inf() ||
$x -> is_nan());
return $x;
}
sub broot {
# calculate $y'th root of $x
# set up parameters
my ($class, $x, $y, @r) = ref($_[0]) && ref($_[0]) eq ref($_[1])
? (ref($_[0]), @_)
: objectify(2, @_);
# Don't modify constant (read-only) objects.
return $x if $x -> modify('broot');
# Handle trivial cases.
return $x -> bnan(@r) if $x -> is_nan() || $y -> is_nan();
if ($x -> is_neg()) {
# -27 ** (1/3) = -(27 ** (1/3)) = -3
return $x -> broot($y -> copy() -> bneg(), @r) -> bneg()
if ($x -> is_int() && $y -> is_int() &&
$y -> is_neg() && $y -> is_odd());
return $x -> _upg -> broot($y, @r) if $class -> upgrade();
return $x -> bnan(@r);
}
# NaN handling: $x ** 1/0, x or y NaN, or y inf/-inf or y == 0
return $x -> bnan(@r) if ($x->{sign} !~ /^\+/ || $y -> is_zero() ||
$y->{sign} !~ /^\+$/);
# Trivial cases.
return $x if ($x -> is_zero() || $x -> is_one() ||
$x -> is_inf() || $y -> is_one());
# we need to limit the accuracy to protect against overflow
my $fallback = 0;
my (@params, $scale);
($x, @params) = $x->_find_round_parameters(@r);
return $x if $x -> is_nan(); # error in _find_round_parameters?
# no rounding at all, so must use fallback
if (scalar @params == 0) {
# simulate old behaviour
$params[0] = $class -> div_scale(); # and round to it as accuracy
$scale = $params[0]+4; # at least four more for proper round
$params[2] = $r[2]; # round mode by caller or undef
$fallback = 1; # to clear a/p afterwards
} else {
# the 4 below is empirical, and there might be cases where it is not
# enough...
$scale = abs($params[0] || $params[1]) + 4; # take whatever is defined
}
# When user set globals, they would interfere with our calculation, so
# disable them and later re-enable them.
my $ab = $class -> accuracy();
my $pb = $class -> precision();
$class -> accuracy(undef);
$class -> precision(undef);
# Disabling upgrading and downgrading is no longer necessary to avoid an
# infinite recursion, but it avoids unnecessary upgrading and downgrading
# in the intermediate computations.
my $upg = $class -> upgrade();
my $dng = $class -> downgrade();
$class -> upgrade(undef);
$class -> downgrade(undef);
# We also need to disable any set A or P on $x (_find_round_parameters took
# them already into account), since these would interfere, too.
$x->{accuracy} = undef;
$x->{precision} = undef;
# remember sign and make $x positive, since -4 ** (1/2) => -2
my $sign = 0;
$sign = 1 if $x->{sign} eq '-';
$x->{sign} = '+';
my $is_two = 0;
if ($y -> isa('Math::BigFloat')) {
$is_two = $y->{sign} eq '+' && $LIB->_is_two($y->{_m})
&& $LIB->_is_zero($y->{_e});
} else {
$is_two = $y == 2;
}
# Normal square root if $y == 2
if ($is_two) {
$x -> bsqrt($scale + 4);
}
# Inverse: $x ** (-1) => 1 / $x
elsif ($y -> is_one('-')) {
$x -> binv($scale + 4);
}
# General case: calculate the broot() as integer result first, and if it
# fits, return it rightaway (but only if $x and $y are integer).
#
# This code should be improved. XXX
else {
# Temporarily disable upgrading in Math::BigInt.
my $mbi_upg = Math::BigInt -> upgrade();
Math::BigInt -> upgrade(undef);
my $done = 0; # not yet
if ($y -> is_int() && $x -> is_int()) {
my $i = $LIB->_copy($x->{_m});
$i = $LIB->_lsft($i, $x->{_e}, 10) unless $LIB->_is_zero($x->{_e});
my $int = Math::BigInt -> bzero();
$int->{value} = $i;
$int -> broot($y -> as_int());
# if ($exact)
if ($int -> copy() -> bpow($y -> as_int()) == $x -> as_int()) {
# found result, return it
$x->{_m} = $int->{value};
$x->{_e} = $LIB->_zero();
$x->{_es} = '+';
$x -> bnorm();
$done = 1;
}
}
if ($done == 0) {
my $u = $class -> bone() -> bdiv($y, $scale+4);
$u->{accuracy} = undef;
$u->{precision} = undef;
$x -> bpow($u, $scale+4); # el cheapo
}
Math::BigInt -> upgrade($mbi_upg);
}
$x -> bneg() if $sign == 1;
# shortcut to not run through _find_round_parameters again
if (defined $params[0]) {
$x -> bround($params[0], $params[2]); # then round accordingly
} else {
$x -> bfround($params[1], $params[2]); # then round accordingly
}
if ($fallback) {
# clear a/p after round, since user did not request it
$x->{accuracy} = undef;
$x->{precision} = undef;
}
# Restore globals. We need to do it like this, because setting one
# undefines the other.
if (defined $ab) {
$class -> accuracy($ab);
} else {
$class -> precision($pb);
}
$class -> upgrade($upg);
$class -> downgrade($dng);
$x -> round(@r);
$x -> _dng() if ($x -> is_int() ||
$x -> is_inf() ||
$x -> is_nan());
return $x;
}
sub bmuladd {
# multiply two numbers and add the third to the result
# set up parameters
my ($class, $x, $y, $z, @r)
= ref($_[0]) && ref($_[0]) eq ref($_[1]) && ref($_[1]) eq ref($_[2])
? (ref($_[0]), @_)
: objectify(3, @_);
# Don't modify constant (read-only) objects.
return $x if $x -> modify('bmuladd');
# At least one of x, y, and z is a NaN
return $x -> bnan(@r) if ($x -> is_nan() ||
$y -> is_nan() ||
$z -> is_nan());
# At least one of x, y, and z is an Inf
if ($x -> is_inf("-")) {
if ($y -> is_neg()) { # x = -inf, y < 0
if ($z -> is_inf("-")) {
return $x -> bnan(@r);
} else {
return $x -> binf("+", @r);
}
} elsif ($y -> is_zero()) { # x = -inf, y = 0
return $x -> bnan(@r);
} else { # x = -inf, y > 0
if ($z->{sign} eq "+inf") {
return $x -> bnan(@r);
} else {
return $x -> binf("-", @r);
}
}
} elsif ($x->{sign} eq "+inf") {
if ($y -> is_neg()) { # x = +inf, y < 0
if ($z->{sign} eq "+inf") {
return $x -> bnan(@r);
} else {
return $x -> binf("-", @r);
}
} elsif ($y -> is_zero()) { # x = +inf, y = 0
return $x -> bnan(@r);
} else { # x = +inf, y > 0
if ($z -> is_inf("-")) {
return $x -> bnan(@r);
} else {
return $x -> binf("+", @r);
}
}
} elsif ($x -> is_neg()) {
if ($y -> is_inf("-")) { # -inf < x < 0, y = -inf
if ($z -> is_inf("-")) {
return $x -> bnan(@r);
} else {
return $x -> binf("+", @r);
}
} elsif ($y->{sign} eq "+inf") { # -inf < x < 0, y = +inf
if ($z->{sign} eq "+inf") {
return $x -> bnan(@r);
} else {
return $x -> binf("-", @r);
}
} else { # -inf < x < 0, -inf < y < +inf
if ($z -> is_inf("-")) {
return $x -> binf("-", @r);
} elsif ($z->{sign} eq "+inf") {
return $x -> binf("+", @r);
}
}
} elsif ($x -> is_zero()) {
if ($y -> is_inf("-")) { # x = 0, y = -inf
return $x -> bnan(@r);
} elsif ($y->{sign} eq "+inf") { # x = 0, y = +inf
return $x -> bnan(@r);
} else { # x = 0, -inf < y < +inf
if ($z -> is_inf("-")) {
return $x -> binf("-", @r);
} elsif ($z->{sign} eq "+inf") {
return $x -> binf("+", @r);
}
}
} elsif ($x -> is_pos()) {
if ($y -> is_inf("-")) { # 0 < x < +inf, y = -inf
if ($z->{sign} eq "+inf") {
return $x -> bnan(@r);
} else {
return $x -> binf("-", @r);
}
} elsif ($y->{sign} eq "+inf") { # 0 < x < +inf, y = +inf
if ($z -> is_inf("-")) {
return $x -> bnan(@r);
} else {
return $x -> binf("+", @r);
}
} else { # 0 < x < +inf, -inf < y < +inf
if ($z -> is_inf("-")) {
return $x -> binf("-", @r);
} elsif ($z->{sign} eq "+inf") {
return $x -> binf("+", @r);
}
}
}
# At this point, we know that x, y, and z are finite numbers
# Rather than copying $y and/or $z, perhaps we should assign the output to
# a temporary $x value, and assign the final result to $x? XXX
$y = $y -> copy() if refaddr($y) eq refaddr($x);
$z = $z -> copy() if refaddr($z) eq refaddr($x);
# aEb * cEd = (a*c)E(b+d)
$x->{_m} = $LIB->_mul($x->{_m}, $y->{_m});
($x->{_e}, $x->{_es})
= $LIB -> _sadd($x->{_e}, $x->{_es}, $y->{_e}, $y->{_es});
$r[3] = $y; # no push!
# adjust sign:
$x->{sign} = $x->{sign} ne $y->{sign} ? '-' : '+';
# take lower of the two e's and adapt m1 to it to match m2
my $e = $z->{_e};
$e = $LIB->_zero() if !defined $e; # if no BFLOAT?
$e = $LIB->_copy($e); # make copy (didn't do it yet)
my $es;
($e, $es) = $LIB -> _ssub($e, $z->{_es} || '+', $x->{_e}, $x->{_es});
my $add = $LIB->_copy($z->{_m});
if ($es eq '-') # < 0
{
$x->{_m} = $LIB->_lsft($x->{_m}, $e, 10);
($x->{_e}, $x->{_es}) = $LIB -> _sadd($x->{_e}, $x->{_es}, $e, $es);
} elsif (!$LIB->_is_zero($e)) # > 0
{
$add = $LIB->_lsft($add, $e, 10);
}
# else: both e are the same, so just leave them
if ($x->{sign} eq $z->{sign}) {
# add
$x->{_m} = $LIB->_add($x->{_m}, $add);
} else {
($x->{_m}, $x->{sign}) =
$LIB -> _sadd($x->{_m}, $x->{sign}, $add, $z->{sign});
}
# delete trailing zeros, then round
$x -> bnorm() -> round(@r);
$x -> _dng() if ($x -> is_int() ||
$x -> is_inf() ||
$x -> is_nan());
return $x;
}
sub bmodpow {
# takes a very large number to a very large exponent in a given very
# large modulus, quickly, thanks to binary exponentiation. Supports
# negative exponents.
my ($class, $num, $exp, $mod, @r)
= ref($_[0]) && ref($_[0]) eq ref($_[1]) && ref($_[1]) eq ref($_[2])
? (ref($_[0]), @_)
: objectify(3, @_);
# Don't modify constant (read-only) objects.
return $num if $num -> modify('bmodpow');
return $num -> bnan(@r)
if $mod -> is_nan() || $exp -> is_nan() || $mod -> is_nan();
# check modulus for valid values
return $num -> bnan(@r) if $mod->{sign} ne '+' || $mod -> is_zero();
# check exponent for valid values
if ($exp->{sign} =~ /\w/) {
# i.e., if it's NaN, +inf, or -inf...
return $num -> bnan(@r);
}
$num -> bmodinv($mod, @r) if $exp->{sign} eq '-';
# check num for valid values (also NaN if there was no inverse but $exp < 0)
return $num -> bnan(@r) if $num->{sign} !~ /^[+-]$/;
# $mod is positive, sign on $exp is ignored, result also positive
# XXX TODO: speed it up when all three numbers are integers
$num -> bpow($exp) -> bmod($mod);
$num -> round(@r);
$num -> _dng() if ($num -> is_int() ||
$num -> is_inf() ||
$num -> is_nan());
return $num;
}
sub blog {
# Return the logarithm of the operand. If a second operand is defined, that
# value is used as the base, otherwise the base is assumed to be Euler's
# constant.
my ($class, $x, $base, @r);
# Only objectify the base if it is defined, since an undefined base, as in
# $x->blog() or $x->blog(undef) signals that the base is Euler's number =
# 2.718281828...
if (!ref($_[0]) && $_[0] =~ /^[A-Za-z]|::/) {
# E.g., Math::BigFloat->blog(256, 2)
($class, $x, $base, @r) =
defined $_[2] ? objectify(2, @_) : objectify(1, @_);
} else {
# E.g., $x->blog(2) or the deprecated Math::BigFloat::blog(256, 2)
($class, $x, $base, @r) =
defined $_[1] ? objectify(2, @_) : objectify(1, @_);
}
# Don't modify constant (read-only) objects.
return $x if $x -> modify('blog');
# Handle all exception cases and all trivial cases. I have used Wolfram
# Alpha (http://www.wolframalpha.com) as the reference for these cases.
return $x -> bnan(@r) if $x -> is_nan();
if (defined $base) {
$base = $class -> new($base)
unless defined(blessed($base)) && $base -> isa(__PACKAGE__);
if ($base -> is_nan() || $base -> is_one()) {
return $x -> bnan(@r);
} elsif ($base -> is_inf() || $base -> is_zero()) {
return $x -> bnan(@r) if $x -> is_inf() || $x -> is_zero();
return $x -> bzero(@r);
} elsif ($base -> is_negative()) { # -inf < base < 0
return $x -> bzero(@r) if $x -> is_one(); # x = 1
return $x -> bone('+', @r) if $x == $base; # x = base
# we can't handle these cases, so upgrade, if we can
return $x -> _upg() -> blog($base, @r) if $class -> upgrade();
return $x -> bnan(@r);
}
return $x -> bone(@r) if $x == $base; # 0 < base && 0 < x < inf
}
if ($x -> is_inf()) { # x = +/-inf
my $sign = defined($base) && $base < 1 ? '-' : '+';
return $x -> binf($sign, @r);
} elsif ($x -> is_neg()) { # -inf < x < 0
return $x -> _upg() -> blog($base, @r) if $class -> upgrade();
return $x -> bnan(@r);
} elsif ($x -> is_one()) { # x = 1
return $x -> bzero(@r);
} elsif ($x -> is_zero()) { # x = 0
my $sign = defined($base) && $base < 1 ? '+' : '-';
return $x -> binf($sign, @r);
}
# we need to limit the accuracy to protect against overflow
my $fallback = 0;
my ($scale, @params);
($x, @params) = $x->_find_round_parameters(@r);
# no rounding at all, so must use fallback
if (scalar @params == 0) {
# simulate old behaviour
$params[0] = $class -> div_scale(); # and round to it as accuracy
$params[1] = undef; # P = undef
$scale = $params[0]+4; # at least four more for proper round
$params[2] = $r[2]; # round mode by caller or undef
$fallback = 1; # to clear a/p afterwards
} else {
# the 4 below is empirical, and there might be cases where it is not
# enough...
$scale = abs($params[0] || $params[1]) + 4; # take whatever is defined
}
# When user set globals, they would interfere with our calculation, so
# disable them and later re-enable them.
my $ab = $class -> accuracy();
my $pb = $class -> precision();
$class -> accuracy(undef);
$class -> precision(undef);
# Disabling upgrading and downgrading is no longer necessary to avoid an
# infinite recursion, but it avoids unnecessary upgrading and downgrading
# in the intermediate computations.
my $upg = $class -> upgrade();
my $dng = $class -> downgrade();
$class -> upgrade(undef);
$class -> downgrade(undef);
# We also need to disable any set A or P on $x (_find_round_parameters took
# them already into account), since these would interfere, too.
$x->{accuracy} = undef;
$x->{precision} = undef;
my $done = 0;
# If both $x and $base are integers, try to calculate an integer result
# first. This is very fast, and if the exact result was found, we are done.
if (defined($base) && $base -> is_int() && $x -> is_int()) {
my $x_lib = $LIB -> _new($x -> bdstr());
my $b_lib = $LIB -> _new($base -> bdstr());
($x_lib, my $exact) = $LIB -> _log_int($x_lib, $b_lib);
if ($exact) {
$x->{_m} = $x_lib;
$x->{_e} = $LIB -> _zero();
$x -> bnorm();
$done = 1;
}
}
# If the integer result was not accurate, compute the natural logarithm
# log($x) (using reduction by 10 and possibly also by 2), and if a
# different base was requested, convert the result with log($x)/log($base).
unless ($done) {
$x -> _log_10($scale);
if (defined $base) {
# log_b(x) = ln(x) / ln(b), so compute ln(b)
my $base_log_e = $base -> copy() -> _log_10($scale);
$x -> bdiv($base_log_e, $scale);
}
}
# shortcut to not run through _find_round_parameters again
if (defined $params[0]) {
$x -> bround($params[0], $params[2]); # then round accordingly
} else {
$x -> bfround($params[1], $params[2]); # then round accordingly
}
if ($fallback) {
# clear a/p after round, since user did not request it
$x->{accuracy} = undef;
$x->{precision} = undef;
}
# Restore globals. We need to do it like this, because setting one
# undefines the other.
if (defined $ab) {
$class -> accuracy($ab);
} else {
$class -> precision($pb);
}
$class -> upgrade($upg);
$class -> downgrade($dng);
$x -> round(@r);
return $x -> _dng() if $x -> is_int();
return $x;
}
sub bexp {
# Calculate e ** X (Euler's number to the power of X)
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
# Don't modify constant (read-only) objects.
return $x if $x -> modify('bexp');
return $x -> bnan(@r) if $x -> is_nan();
return $x -> binf(@r) if $x -> is_inf("+");
return $x -> bzero(@r) if $x -> is_inf("-");
# Get the rounding parameters, if any.
my $fallback = 0;
my ($scale, @params);
($x, @params) = $x -> _find_round_parameters(@r);
# Error in _find_round_parameters?
return $x -> bnan(@r) if $x -> is_nan();
return $x -> bone(@r) if $x -> is_zero();
# If no rounding parameters are give, use fallback.
if (!@params) {
$params[0] = $class -> div_scale(); # fallback accuracy
$params[1] = undef; # no precision
$params[2] = $r[2]; # rounding mode
$scale = $params[0];
$fallback = 1; # to clear a/p afterwards
} else {
if (defined($params[0])) {
$scale = $params[0];
} else {
# We perform the computations below using accuracy only, not
# precision, so when precision is given, we need to "convert" this
# to accuracy. To do that, we need to know, at least approximately,
# how many digits there will be in the final result.
#
# log10(exp($x)) = log(exp($x)) / log(10) = $x / log(10)
#$scale = 1 + int(log($ms) / log(10) + $es) - $params[1];
my $ndig = $x -> numify() / log(10);
$scale = 1 + int($ndig) - $params[1];
}
}
# Add extra digits to reduce the consequence of round-off errors in the
# intermediate computations.
$scale += 4;
if (!$x -> isa('Math::BigFloat')) {
$x = Math::BigFloat -> new($x);
$class = ref($x);
}
# When user set globals, they would interfere with our calculation, so
# disable them and later re-enable them.
my $ab = $class -> accuracy();
my $pb = $class -> precision();
$class -> accuracy(undef);
$class -> precision(undef);
# Disabling upgrading and downgrading is no longer necessary to avoid an
# infinite recursion, but it avoids unnecessary upgrading and downgrading
# in the intermediate computations.
my $upg = $class -> upgrade();
my $dng = $class -> downgrade();
$class -> upgrade(undef);
$class -> downgrade(undef);
# We also need to disable any set A or P on $x (_find_round_parameters took
# them already into account), since these would interfere, too.
$x->{accuracy} = undef;
$x->{precision} = undef;
my $x_orig = $x -> copy();
# We use the following Taylor series:
# x x^2 x^3 x^4
# e = 1 + --- + --- + --- + --- ...
# 1! 2! 3! 4!
# The difference for each term is X and N, which would result in:
# 2 copy, 2 mul, 2 add, 1 inc, 1 div operations per term
# But it is faster to compute exp(1) and then raising it to the
# given power, esp. if $x is really big and an integer because:
# * The numerator is always 1, making the computation faster
# * the series converges faster in the case of x == 1
# * We can also easily check when we have reached our limit: when the
# term to be added is smaller than "1E$scale", we can stop - f.i.
# scale == 5, and we have 1/40320, then we stop since 1/40320 < 1E-5.
# * we can compute the *exact* result by simulating bigrat math:
# 1 1 gcd(3, 4) = 1 1*24 + 1*6 5
# - + - = ---------- = --
# 6 24 6*24 24
# We do not compute the gcd() here, but simple do:
# 1 1 1*24 + 1*6 30
# - + - = --------- = --
# 6 24 6*24 144
# In general:
# a c a*d + c*b and note that c is always 1 and d = (b*f)
# - + - = ---------
# b d b*d
# This leads to: which can be reduced by b to:
# a 1 a*b*f + b a*f + 1
# - + - = --------- = -------
# b b*f b*b*f b*f
# The first terms in the series are:
# 1 1 1 1 1 1 1 1 13700
# -- + -- + -- + -- + -- + --- + --- + ---- = -----
# 1 1 2 6 24 120 720 5040 5040
# Note that we cannot simply reduce 13700/5040 to 685/252, but must keep
# the numerator and the denominator!
if ($scale <= 75) {
# set $x directly from a cached string form
$x->{_m} = $LIB->_new("2718281828459045235360287471352662497757" .
"2470936999595749669676277240766303535476");
$x->{sign} = '+';
$x->{_es} = '-';
$x->{_e} = $LIB->_new(79);
} else {
# compute A and B so that e = A / B.
# After some terms we end up with this, so we use it as a starting
# point:
my $A = $LIB->_new("9093339520860578540197197" .
"0164779391644753259799242");
my $F = $LIB->_new(42);
my $step = 42;
# Compute number of steps needed to get $A and $B sufficiently large.
my $steps = _len_to_steps($scale - 4);
# print STDERR "# Doing $steps steps for ", $scale-4, " digits\n";
while ($step++ <= $steps) {
# calculate $a * $f + 1
$A = $LIB -> _mul($A, $F);
$A = $LIB -> _inc($A);
# increment f
$F = $LIB -> _inc($F);
}
# Compute $B as factorial of $steps (this is faster than doing it
# manually)
my $B = $LIB->_fac($LIB->_new($steps));
# print "A ", $LIB->_str($A), "\nB ", $LIB->_str($B), "\n";
# compute A/B with $scale digits in the result (truncate, not round)
$A = $LIB->_lsft($A, $LIB->_new($scale), 10);
$A = $LIB->_div($A, $B);
$x->{_m} = $A;
$x->{sign} = '+';
$x->{_es} = '-';
$x->{_e} = $LIB->_new($scale);
}
# Now $x contains now an estimate of e, with some additional digits.
if ($x_orig -> is_one()) {
# else just round the already computed result
$x->{accuracy} = undef;
$x->{precision} = undef;
# shortcut to not run through _find_round_parameters again
if (defined $params[0]) {
$x -> bround($params[0], $params[2]); # then round accordingly
} else {
$x -> bfround($params[1], $params[2]); # then round accordingly
}
} else {
# Use the fact exp(x) = exp(x/n)**n. In our case, n = 2**i for some
# integer i. We use this to compute exp(y) where y = x / (2**i) and
# 1 <= |y| < 2.
#
# The code below is similar to the code found in to_ieee754().
# We need to find the base 2 exponent. First make an estimate of the
# base 2 exponent, before adjusting it below. We could skip this
# estimation and go straight to the while-loops below, but the loops
# are slow, especially when the final exponent is far from zero and
# even more so if the number of digits is large. This initial
# estimation speeds up the computation dramatically.
#
# log2($m * 10**$e) = log10($m + 10**$e) * log(10)/log(2)
# = (log10($m) + $e) * log(10)/log(2)
# = (log($m)/log(10) + $e) * log(10)/log(2)
my ($m, $e) = $x_orig -> nparts();
my $ms = $m -> numify();
my $es = $e -> numify();
# We start off by initializing the exponent to zero and the mantissa to
# the input value. Then we increase the mantissa and decrease the
# exponent, or vice versa, until the mantissa is in the desired range
# or we hit one of the limits for the exponent.
my $mant = $x_orig -> copy() -> babs();
my $expo;
my $one = $class -> bone();
my $two = $class -> new("2");
my $half = $class -> new("0.5");
my $expo_est = (log(abs($ms))/log(10) + $es) * log(10)/log(2);
$expo_est = int($expo_est);
# Don't multiply by a number raised to a negative exponent. This will
# cause a division, whose result is truncated to some fixed number of
# digits. Instead, multiply by the inverse number raised to a positive
# exponent.
$expo = $class -> new($expo_est);
if ($expo_est > 0) {
$mant -> bmul($half -> copy() -> bpow($expo));
} elsif ($expo_est < 0) {
my $expo_abs = $expo -> copy() -> bneg();
$mant -> bmul($two -> copy() -> bpow($expo_abs));
}
# Final adjustment of the estimate above.
while ($mant -> bcmp($two) >= 0) { # $mant <= $two
$mant -> bmul($half);
$expo -> binc();
}
while ($mant -> bcmp($one) < 0) { # $mant > $one
$mant -> bmul($two);
$expo -> bdec();
}
# Because of the upscaling, we need some additional digits.
my $rescale = int($scale + abs($expo) * log(2) / log(10) + 1);
$rescale = 4 if $rescale < 4;
$x -> bpow($mant, $rescale);
my $pow2 = $two -> bpow($expo, $rescale);
$pow2 -> bneg() if $x_orig -> is_negative();
# The bpow() below fails with the GMP and GMPz libraries if abs($pow2)
# >= 2**30 = 1073741824. With the Pari library, it fails already when
# abs($pow) >= 2**13 = 8192. With the Calc library, it is rediculously
# slow when abs($pow2) is large. Fixme?
croak "cannot compute bexp(); input value is too large"
if $pow2 -> copy() -> babs() -> bcmp("1073741824") >= 0;
$x -> bpow($pow2, $rescale);
# Rounding parameters given as arguments currently don't override
# instance variables, so accuracy (which is set in the computations
# above) must be undefined before rounding. Fixme.
$x->{accuracy} = undef;
$x -> round(@params);
}
if ($fallback) {
# clear a/p after round, since user did not request it
$x->{accuracy} = undef;
$x->{precision} = undef;
}
# Restore globals. We need to do it like this, because setting one
# undefines the other.
if (defined $ab) {
$class -> accuracy($ab);
} else {
$class -> precision($pb);
}
$class -> upgrade($upg);
$class -> downgrade($dng);
# If downgrading, remember to preserve the relevant instance parameters.
# There should be a more elegant way to do this. Fixme.
$x -> round(@r);
$x -> _dng() if $x -> is_int();
$x;
}
sub bilog2 {
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
# Don't modify constant (read-only) objects.
return $x if $x -> modify('bilog2');
return $x -> bnan(@r) if $x -> is_nan();
return $x -> binf("+", @r) if $x -> is_inf("+");
return $x -> binf("-", @r) if $x -> is_zero();
if ($x -> is_neg()) {
return $x -> _upg() -> bilog2(@r) if $class -> upgrade();
return $x -> bnan(@r);
}
if ($x->{_es} eq '-') { # exponent < 0
$x->{_m} = $LIB->_rsft($x->{_m}, $x->{_e}, 10);
} elsif (! $LIB->_is_zero($x->{_e})) { # exponent > 0
$x->{_m} = $LIB->_lsft($x->{_m}, $x->{_e}, 10);
}
$x->{_m} = $LIB -> _ilog2($x->{_m});
$x->{_e} = $LIB -> _zero();
$x -> bnorm() -> round(@r);
$x -> _dng();
return $x;
}
sub bilog10 {
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
# Don't modify constant (read-only) objects.
return $x if $x -> modify('bilog10');
return $x -> bnan(@r) if $x -> is_nan();
return $x -> binf("+", @r) if $x -> is_inf("+");
return $x -> binf("-", @r) if $x -> is_zero();
if ($x -> is_neg()) {
return $x -> _upg() -> bilog10(@r) if $class -> upgrade();
return $x -> bnan(@r);
}
if ($x->{_es} eq '-') { # exponent < 0
$x->{_m} = $LIB->_rsft($x->{_m}, $x->{_e}, 10);
} elsif (! $LIB->_is_zero($x->{_e})) { # exponent > 0
$x->{_m} = $LIB->_lsft($x->{_m}, $x->{_e}, 10);
}
$x->{_m} = $LIB -> _ilog10($x->{_m});
$x->{_e} = $LIB -> _zero();
$x -> bnorm() -> round(@r);
$x -> _dng();
return $x;
}
sub bclog2 {
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
# Don't modify constant (read-only) objects.
return $x if $x -> modify('bclog2');
return $x -> bnan(@r) if $x -> is_nan();
return $x -> binf("+", @r) if $x -> is_inf("+");
return $x -> binf("-", @r) if $x -> is_zero();
if ($x -> is_neg()) {
return $x -> _upg() -> bclog2(@r) if $class -> upgrade();
return $x -> bnan(@r);
}
if ($x->{_es} eq '-') { # exponent < 0
$x->{_m} = $LIB->_rsft($x->{_m}, $x->{_e}, 10);
} elsif (! $LIB->_is_zero($x->{_e})) { # exponent > 0
$x->{_m} = $LIB->_lsft($x->{_m}, $x->{_e}, 10);
}
$x->{_m} = $LIB -> _clog2($x->{_m});
$x->{_e} = $LIB -> _zero();
$x -> bnorm() -> round(@r);
$x -> _dng();
return $x;
}
sub bclog10 {
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
# Don't modify constant (read-only) objects.
return $x if $x -> modify('bclog10');
return $x -> bnan(@r) if $x -> is_nan();
return $x -> binf("+", @r) if $x -> is_inf("+");
return $x -> binf("-", @r) if $x -> is_zero();
if ($x -> is_neg()) {
return $x -> _upg() -> bclog10(@r) if $class -> upgrade();
return $x -> bnan(@r);
}
if ($x->{_es} eq '-') { # exponent < 0
$x->{_m} = $LIB->_rsft($x->{_m}, $x->{_e}, 10);
} elsif (! $LIB->_is_zero($x->{_e})) { # exponent > 0
$x->{_m} = $LIB->_lsft($x->{_m}, $x->{_e}, 10);
}
$x->{_m} = $LIB -> _clog10($x->{_m});
$x->{_e} = $LIB -> _zero();
$x -> bnorm() -> round(@r);
$x -> _dng();
return $x;
}
sub bnok {
# Calculate n over k (binomial coefficient or "choose" function) as
# integer. set up parameters
my ($class, $x, $y, @r) = ref($_[0]) && ref($_[0]) eq ref($_[1])
? (ref($_[0]), @_)
: objectify(2, @_);
carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;
# Don't modify constant (read-only) objects.
return $x if $x -> modify('bnok');
return $x -> bnan() if $x -> is_nan() || $y -> is_nan();
return $x -> bnan() if (($x -> is_finite() && !$x -> is_int()) ||
($y -> is_finite() && !$y -> is_int()));
# This should be implemented without converting to Math::BigInt. XXX
my $xint = $x -> as_int(); # to Math::BigInt
my $yint = $y -> as_int(); # to Math::BigInt
$xint -> bnok($yint);
$xint -> round(@r);
my $xflt = $xint -> as_float();
$x -> {sign} = $xflt -> {sign};
$x -> {_m} = $xflt -> {_m};
$x -> {_es} = $xflt -> {_es};
$x -> {_e} = $xflt -> {_e};
return $x -> _dng();
return $x;
}
sub bperm {
# Calculate n over k (binomial coefficient or "choose" function) as
# integer. set up parameters
my ($class, $x, $y, @r) = ref($_[0]) && ref($_[0]) eq ref($_[1])
? (ref($_[0]), @_)
: objectify(2, @_);
carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;
# Don't modify constant (read-only) objects.
return $x if $x -> modify('bperm');
return $x -> bnan() if $x -> is_nan() || $y -> is_nan();
return $x -> bnan() if (($x -> is_finite() && !$x -> is_int()) ||
($y -> is_finite() && !$y -> is_int()));
# This should be implemented without converting to Math::BigInt. XXX
my $xint = $x -> as_int(); # to Math::BigInt
my $yint = $y -> as_int(); # to Math::BigInt
$xint -> bperm($yint);
$xint -> round(@r);
my $xflt = $xint -> as_float();
$x -> {sign} = $xflt -> {sign};
$x -> {_m} = $xflt -> {_m};
$x -> {_es} = $xflt -> {_es};
$x -> {_e} = $xflt -> {_e};
return $x -> _dng();
return $x;
}
sub bsin {
# Calculate a sinus of x.
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
# First we apply range reduction to x. This is because if x is large, the
# Taylor series converges slowly and requires higher accuracy in the
# intermediate computation. The Taylor series is:
#
# x^3 x^5 x^7 x^9
# sin(x) = x - --- + --- - --- + --- ...
# 3! 5! 7! 9!
# Don't modify constant (read-only) objects.
return $x if $x -> modify('bsin');
return $x -> bzero(@r) if $x -> is_zero();
return $x -> bnan(@r) if $x -> is_nan() || $x -> is_inf();
# Get the rounding parameters, if any.
my $fallback = 0;
my ($scale, @params);
($x, @params) = $x -> _find_round_parameters(@r);
# Error in _find_round_parameters?
return $x -> bnan(@r) if $x -> is_nan();
# If no rounding parameters are given, use fallback.
if (!@params) {
$params[0] = $class -> div_scale(); # fallback accuracy
$params[1] = undef; # no precision
$params[2] = $r[2]; # rounding mode
$scale = $params[0];
$fallback = 1; # to clear a/p afterwards
} else {
if (defined($params[0])) {
$scale = $params[0];
} else {
# We perform the computations below using accuracy only, not
# precision, so when precision is given, we need to "convert" this
# to accuracy.
$scale = 1 - $params[1];
}
}
# Add more digits to the scale if the magnitude of $x is large.
my ($m, $e) = $x -> nparts();
$scale += $e if $x >= 10;
$scale = 4 if $scale < 4;
# When user set globals, they would interfere with our calculation, so
# disable them and later re-enable them
my $ab = $class -> accuracy();
my $pb = $class -> precision();
$class -> accuracy(undef);
$class -> precision(undef);
# Disabling upgrading and downgrading is no longer necessary to avoid an
# infinite recursion, but it avoids unnecessary upgrading and downgrading
# in the intermediate computations.
my $upg = $class -> upgrade();
my $dng = $class -> downgrade();
$class -> upgrade(undef);
$class -> downgrade(undef);
# We also need to disable any set A or P on $x (_find_round_parameters took
# them already into account), since these would interfere, too.
$x->{accuracy} = undef;
$x->{precision} = undef;
my $sin_prev; # the previous approximation of sin(x)
my $sin; # the current approximation of sin(x)
while (1) {
# Compute constants to the current scale.
my $pi = $class -> bpi($scale); # 𝜋
my $twopi = $pi -> copy() -> bmul("2"); # 2𝜋
my $halfpi = $pi -> copy() -> bmul("0.5"); # 𝜋/2
# Use the fact that sin(-x) = -sin(x) to reduce the range to the
# interval to [0,∞).
my $xsgn = $x < 0 ? -1 : 1;
my $x = $x -> copy() -> babs();
# Use the fact that sin(2𝜋x) = sin(x) to reduce the range to the
# interval to [0, 2𝜋).
$x -> bmod($twopi, $scale);
# Use the fact that sin(x+𝜋) = -sin(x) to reduce the range to the
# interval to [0,𝜋).
if ($x -> bcmp($pi) > 0) {
$xsgn = -$xsgn;
$x -> bsub($pi);
}
# Use the fact that sin(𝜋-x) = sin(x) to reduce the range to the
# interval [0,𝜋/2).
if ($x -> bcmp($halfpi) > 0) {
$x -> bsub($pi) -> bneg(); # 𝜋 - x
}
my $tol = $class -> new("1E-". ($scale-1));
my $xsq = $x -> copy() -> bmul($x, $scale) -> bneg();
my $term = $x -> copy();
my $fac = $class -> bone();
my $n = $class -> bone();
$sin = $x -> copy(); # initialize sin(x) to the first term
while (1) {
$n -> binc();
$fac = $n -> copy();
$n -> binc();
$fac -> bmul($n);
$term -> bmul($xsq, $scale) -> bdiv($fac, $scale);
$sin -> badd($term, $scale);
last if $term -> copy() -> babs() -> bcmp($tol) < 0;
}
$sin -> bneg() if $xsgn < 0;
# Rounding parameters given as arguments currently don't override
# instance variables, so accuracy (which is set in the computations
# above) must be undefined before rounding. Fixme.
$sin->{accuracy} = undef;
$sin -> round(@params);
# Compare the current approximation of sin(x) with the previous one,
# and if they are identical, we're done.
if (defined $sin_prev) {
last if $sin -> bcmp($sin_prev) == 0;
}
# If the current approximation of sin(x) is different from the previous
# approximation, double the scale (accuracy) and retry.
$sin_prev = $sin;
$scale *= 2;
}
# Assign the result to the invocand.
%$x = %$sin;
if ($fallback) {
# clear a/p after round, since user did not request it
$x->{accuracy} = undef;
$x->{precision} = undef;
}
# Restore globals. We need to do it like this, because setting one
# undefines the other.
if (defined $ab) {
$class -> accuracy($ab);
} else {
$class -> precision($pb);
}
$class -> upgrade($upg);
$class -> downgrade($dng);
# rounding has already been done
$x -> _dng() if $x -> is_int();
$x;
}
sub bcos {
# Calculate a cosinus of x.
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
# Taylor: x^2 x^4 x^6 x^8
# cos = 1 - --- + --- - --- + --- ...
# 2! 4! 6! 8!
# Don't modify constant (read-only) objects.
return $x if $x -> modify('bcos');
# we need to limit the accuracy to protect against overflow
my $fallback = 0;
my ($scale, @params);
($x, @params) = $x->_find_round_parameters(@r);
# error in _find_round_parameters?
return $x if $x -> is_nan();
return $x -> bnan() if $x -> is_inf();
return $x -> bone(@r) if $x -> is_zero();
# no rounding at all, so must use fallback
if (scalar @params == 0) {
# simulate old behaviour
$params[0] = $class -> div_scale(); # and round to it as accuracy
$params[1] = undef; # disable P
$scale = $params[0] + 4; # at least four more for proper round
$params[2] = $r[2]; # round mode by caller or undef
$fallback = 1; # to clear a/p afterwards
} else {
# the 4 below is empirical, and there might be cases where it is not
# enough...
$scale = abs($params[0] || $params[1]) + 4; # take whatever is defined
}
# When user set globals, they would interfere with our calculation, so
# disable them and later re-enable them.
my $ab = $class -> accuracy();
my $pb = $class -> precision();
$class -> accuracy(undef);
$class -> precision(undef);
# Disabling upgrading and downgrading is no longer necessary to avoid an
# infinite recursion, but it avoids unnecessary upgrading and downgrading
# in the intermediate computations.
my $upg = $class -> upgrade();
my $dng = $class -> downgrade();
$class -> upgrade(undef);
$class -> downgrade(undef);
# We also need to disable any set A or P on $x (_find_round_parameters took
# them already into account), since these would interfere, too.
$x->{accuracy} = undef;
$x->{precision} = undef;
my $over = $x * $x; # X ^ 2
my $x2 = $over -> copy(); # X ^ 2; difference between terms
my $sign = 1; # start with -=
my $below = $class -> new(2);
my $factorial = $class -> new(3);
$x -> bone();
$x->{accuracy} = undef;
$x->{precision} = undef;
my $limit = $class -> new("1E-". ($scale-1));
#my $steps = 0;
while (3 < 5) {
# we calculate the next term, and add it to the last
# when the next term is below our limit, it won't affect the outcome
# anymore, so we stop:
my $next = $over -> copy() -> bdiv($below, $scale);
last if $next -> bacmp($limit) <= 0;
if ($sign == 0) {
$x -> badd($next);
} else {
$x -> bsub($next);
}
$sign = 1-$sign; # alternate
# calculate things for the next term
$over -> bmul($x2); # $x*$x
$below -> bmul($factorial); # n*(n+1)
$factorial -> binc();
$below -> bmul($factorial); # n*(n+1)
$factorial -> binc();
}
# shortcut to not run through _find_round_parameters again
if (defined $params[0]) {
$x -> bround($params[0], $params[2]); # then round accordingly
} else {
$x -> bfround($params[1], $params[2]); # then round accordingly
}
if ($fallback) {
# clear a/p after round, since user did not request it
$x->{accuracy} = undef;
$x->{precision} = undef;
}
# Restore globals. We need to do it like this, because setting one
# undefines the other.
if (defined $ab) {
$class -> accuracy($ab);
} else {
$class -> precision($pb);
}
$class -> upgrade($upg);
$class -> downgrade($dng);
$x -> round(@r);
$x -> _dng() if $x -> is_int();
$x;
}
sub batan {
# Calculate a arcus tangens of x.
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
# taylor: x^3 x^5 x^7 x^9
# atan = x - --- + --- - --- + --- ...
# 3 5 7 9
# Don't modify constant (read-only) objects.
return $x if $x -> modify('batan');
return $x -> bnan(@r) if $x -> is_nan();
# We need to limit the accuracy to protect against overflow.
my $fallback = 0;
my ($scale, @params);
($x, @params) = $x->_find_round_parameters(@r);
# Error in _find_round_parameters?
return $x -> bnan(@r) if $x -> is_nan();
if ($x->{sign} =~ /^[+-]inf\z/) {
# +inf result is PI/2
# -inf result is -PI/2
# calculate PI/2
my $pi = $class -> bpi(@r);
# modify $x in place
$x->{_m} = $pi->{_m};
$x->{_e} = $pi->{_e};
$x->{_es} = $pi->{_es};
# -y => -PI/2, +y => PI/2
$x->{sign} = substr($x->{sign}, 0, 1); # "+inf" => "+"
$x -> {_m} = $LIB->_div($x->{_m}, $LIB->_new(2));
return $x;
}
return $x -> bzero(@r) if $x -> is_zero();
# no rounding at all, so must use fallback
if (scalar @params == 0) {
# simulate old behaviour
$params[0] = $class -> div_scale(); # and round to it as accuracy
$params[1] = undef; # disable P
$scale = $params[0]+4; # at least four more for proper round
$params[2] = $r[2]; # round mode by caller or undef
$fallback = 1; # to clear a/p afterwards
} else {
# the 4 below is empirical, and there might be cases where it is not
# enough...
$scale = abs($params[0] || $params[1]) + 4; # take whatever is defined
}
# 1 or -1 => PI/4
# inlined is_one() && is_one('-')
if ($LIB->_is_one($x->{_m}) && $LIB->_is_zero($x->{_e})) {
my $pi = $class -> bpi($scale - 3);
# modify $x in place
$x->{_m} = $pi->{_m};
$x->{_e} = $pi->{_e};
$x->{_es} = $pi->{_es};
# leave the sign of $x alone (+1 => +PI/4, -1 => -PI/4)
$x->{_m} = $LIB->_div($x->{_m}, $LIB->_new(4));
return $x;
}
# When user set globals, they would interfere with our calculation, so
# disable them and later re-enable them.
my $ab = $class -> accuracy();
my $pb = $class -> precision();
$class -> accuracy(undef);
$class -> precision(undef);
# Disable upgrading and downgrading.
my $upg = $class -> upgrade();
my $dng = $class -> downgrade();
$class -> upgrade(undef);
$class -> downgrade(undef);
# We also need to disable any set A or P on $x (_find_round_parameters took
# them already into account), since these would interfere, too.
$x->{accuracy} = undef;
$x->{precision} = undef;
# This series is only valid if -1 < x < 1, so for other x we need to
# calculate PI/2 - atan(1/x):
my $pi = undef;
if ($x -> bacmp($x -> copy() -> bone) >= 0) {
# calculate PI/2
$pi = $class -> bpi($scale - 3);
$pi->{_m} = $LIB->_div($pi->{_m}, $LIB->_new(2));
# calculate 1/$x:
my $x_copy = $x -> copy();
# modify $x in place
$x -> bone();
$x -> bdiv($x_copy, $scale);
}
my $fmul = 1;
foreach (0 .. int($scale / 20)) {
$fmul *= 2;
$x -> bdiv($x -> copy() -> bmul($x) -> binc() -> bsqrt($scale + 4) -> binc(),
$scale + 4);
}
my $over = $x * $x; # X ^ 2
my $x2 = $over -> copy(); # X ^ 2; difference between terms
$over -> bmul($x); # X ^ 3 as starting value
my $sign = 1; # start with -=
my $below = $class -> new(3);
my $two = $class -> new(2);
$x->{accuracy} = undef;
$x->{precision} = undef;
my $limit = $class -> new("1E-". ($scale-1));
#my $steps = 0;
while (1) {
# We calculate the next term, and add it to the last. When the next
# term is below our limit, it won't affect the outcome anymore, so we
# stop:
my $next = $over -> copy() -> bdiv($below, $scale);
last if $next -> bacmp($limit) <= 0;
if ($sign == 0) {
$x -> badd($next);
} else {
$x -> bsub($next);
}
$sign = 1 - $sign; # alternatex
# calculate things for the next term
$over -> bmul($x2); # $x*$x
$below -> badd($two); # n += 2
}
$x -> bmul($fmul);
if (defined $pi) {
my $x_copy = $x -> copy();
# modify $x in place
$x->{_m} = $pi->{_m};
$x->{_e} = $pi->{_e};
$x->{_es} = $pi->{_es};
# PI/2 - $x
$x -> bsub($x_copy);
}
# Shortcut to not run through _find_round_parameters again.
if (defined $params[0]) {
$x -> bround($params[0], $params[2]); # then round accordingly
} else {
$x -> bfround($params[1], $params[2]); # then round accordingly
}
if ($fallback) {
# Clear a/p after round, since user did not request it.
$x->{accuracy} = undef;
$x->{precision} = undef;
}
# Restore globals. We need to do it like this, because setting one
# undefines the other.
if (defined $ab) {
$class -> accuracy($ab);
} else {
$class -> precision($pb);
}
$class -> upgrade($upg);
$class -> downgrade($dng);
return $x -> _dng() if ($x -> is_int() ||
$x -> is_inf());
$x;
}
sub batan2 {
# $y -> batan2($x) returns the arcus tangens of $y / $x.
# Set up parameters.
my ($class, $y, $x, @r) = ref($_[0]) && ref($_[0]) eq ref($_[1])
? (ref($_[0]), @_)
: objectify(2, @_);
# Don't modify constant (read-only) objects.
return $y if $y -> modify('batan2');
# Handle all NaN cases.
return $y -> bnan() if $x -> is_nan() || $y -> is_nan();
# We need to limit the accuracy to protect against overflow.
my $fallback = 0;
my ($scale, @params);
($y, @params) = $y -> _find_round_parameters(@r);
# Error in _find_round_parameters?
return $y if $y -> is_nan();
# No rounding at all, so must use fallback.
if (scalar @params == 0) {
# Simulate old behaviour
$params[0] = $class -> div_scale(); # and round to it as accuracy
$params[1] = undef; # disable P
$scale = $params[0] + 4; # at least four more for proper round
$params[2] = $r[2]; # round mode by caller or undef
$fallback = 1; # to clear a/p afterwards
} else {
# The 4 below is empirical, and there might be cases where it is not
# enough ...
$scale = abs($params[0] || $params[1]) + 4; # take whatever is defined
}
if ($x -> is_inf("+")) { # x = inf
if ($y -> is_inf("+")) { # y = inf
$y -> bpi($scale) -> bmul("0.25"); # pi/4
} elsif ($y -> is_inf("-")) { # y = -inf
$y -> bpi($scale) -> bmul("-0.25"); # -pi/4
} else { # -inf < y < inf
return $y -> bzero(@r); # 0
}
} elsif ($x -> is_inf("-")) { # x = -inf
if ($y -> is_inf("+")) { # y = inf
$y -> bpi($scale) -> bmul("0.75"); # 3/4 pi
} elsif ($y -> is_inf("-")) { # y = -inf
$y -> bpi($scale) -> bmul("-0.75"); # -3/4 pi
} elsif ($y >= 0) { # y >= 0
$y -> bpi($scale); # pi
} else { # y < 0
$y -> bpi($scale) -> bneg(); # -pi
}
} elsif ($x > 0) { # 0 < x < inf
if ($y -> is_inf("+")) { # y = inf
$y -> bpi($scale) -> bmul("0.5"); # pi/2
} elsif ($y -> is_inf("-")) { # y = -inf
$y -> bpi($scale) -> bmul("-0.5"); # -pi/2
} else { # -inf < y < inf
$y -> bdiv($x, $scale) -> batan($scale); # atan(y/x)
}
} elsif ($x < 0) { # -inf < x < 0
my $pi = $class -> bpi($scale);
if ($y >= 0) { # y >= 0
$y -> bdiv($x, $scale) -> batan() # atan(y/x) + pi
-> badd($pi);
} else { # y < 0
$y -> bdiv($x, $scale) -> batan() # atan(y/x) - pi
-> bsub($pi);
}
} else { # x = 0
if ($y > 0) { # y > 0
$y -> bpi($scale) -> bmul("0.5"); # pi/2
} elsif ($y < 0) { # y < 0
$y -> bpi($scale) -> bmul("-0.5"); # -pi/2
} else { # y = 0
return $y -> bzero(@r); # 0
}
}
$y -> round(@r);
if ($fallback) {
$y->{accuracy} = undef;
$y->{precision} = undef;
}
return $y;
}
sub bfac {
# (BFLOAT or num_str, BFLOAT or num_str) return BFLOAT
# compute factorial number, modifies first argument
# set up parameters
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
# Don't modify constant (read-only) objects.
return $x if $x -> modify('bfac');
return $x -> bnan(@r) if $x -> is_nan() || $x -> is_inf("-");
return $x -> binf("+", @r) if $x -> is_inf("+");
return $x -> bnan(@r) if $x -> is_neg() || !$x -> is_int();
return $x -> bone(@r) if $x -> is_zero() || $x -> is_one();
if ($x -> is_neg() || !$x -> is_int()) {
return $x -> _upg() -> bfac(@r) if $class -> upgrade();
return $x -> bnan(@r);
}
if (! $LIB->_is_zero($x->{_e})) {
$x->{_m} = $LIB->_lsft($x->{_m}, $x->{_e}, 10); # change 12e1 to 120e0
$x->{_e} = $LIB->_zero(); # normalize
$x->{_es} = '+';
}
$x->{_m} = $LIB->_fac($x->{_m}); # calculate factorial
$x -> bnorm(); # norm again
$x -> round(@r);
$x -> _dng();
return $x;
}
sub bdfac {
# compute double factorial, modify $x in place
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
# Don't modify constant (read-only) objects.
return $x if $x -> modify('bdfac');
return $x -> bnan(@r) if $x -> is_nan() || $x -> is_inf("-");
return $x -> binf("+", @r) if $x -> is_inf("+");
return $x -> bnan(@r) if $x <= -2 || !$x -> is_int();
return $x -> bone(@r) if $x <= 1;
croak("bdfac() requires a newer version of the $LIB library.")
unless $LIB -> can('_dfac');
if (! $LIB->_is_zero($x->{_e})) {
$x->{_m} = $LIB->_lsft($x->{_m}, $x->{_e}, 10); # change 12e1 to 120e0
$x->{_e} = $LIB->_zero(); # normalize
$x->{_es} = '+';
}
$x->{_m} = $LIB->_dfac($x->{_m}); # calculate factorial
$x -> bnorm(); # norm again
$x -> round(@r);
$x -> _dng();
return $x;
}
sub btfac {
# compute triple factorial
# set up parameters
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
# Don't modify constant (read-only) objects.
return $x if $x -> modify('btfac');
return $x -> bnan(@r) if $x -> is_nan() || $x -> is_inf("-");
return $x -> binf("+", @r) if $x -> is_inf("+");
if ($x <= -3 || !$x -> is_int()) {
return $x -> _upg() -> btfac(@r) if $class -> upgrade();
return $x -> bnan(@r);
}
my $k = $class -> new("3");
return $x -> bnan(@r) if $x <= -$k;
my $one = $class -> bone();
return $x -> bone(@r) if $x <= $one;
my $f = $x -> copy();
while ($f -> bsub($k) > $one) {
$x = $x -> bmul($f);
}
$x -> round(@r);
$x -> _dng();
return $x;
}
sub bmfac {
my ($class, $x, $k, @r) = ref($_[0]) && ref($_[0]) eq ref($_[1])
? (ref($_[0]), @_)
: objectify(2, @_);
# Don't modify constant (read-only) objects.
return $x if $x -> modify('bmfac');
return $x -> bnan(@r) if $x -> is_nan() || $x -> is_inf("-") ||
!$k -> is_pos();
return $x -> binf("+", @r) if $x -> is_inf("+");
return $x -> bround(@r) if $k -> is_inf("+");
return $x -> bnan(@r) if !$x -> is_int() || !$k -> is_int();
return $x -> bnan(@r) if $k < 1 || $x <= -$k;
my $one = $class -> bone();
return $x -> bone(@r) if $x <= $one;
my $f = $x -> copy();
while ($f -> bsub($k) > $one) {
$x -> bmul($f);
}
$x -> round(@r);
$x -> _dng();
return $x;
}
sub bfib {
# compute Fibonacci number(s)
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
croak("bfib() requires a newer version of the $LIB library.")
unless $LIB -> can('_fib');
# Don't modify constant (read-only) objects.
return $x if $x -> modify('bfib');
# List context.
if (wantarray) {
croak("bfib() can't return an infinitely long list of numbers")
if $x -> is_inf();
return if $x -> is_nan() || !$x -> is_int();
# The following places a limit on how large $x can be. Should this
# limit be removed? XXX
my $n = $x -> numify();
my @y;
{
$y[0] = $x -> copy() -> babs();
$y[0]{_m} = $LIB -> _zero();
$y[0]{_e} = $LIB -> _zero();
last if $n == 0;
$y[1] = $y[0] -> copy();
$y[1]{_m} = $LIB -> _one();
$y[1]{_e} = $LIB -> _zero();
last if $n == 1;
for (my $i = 2 ; $i <= abs($n) ; $i++) {
$y[$i] = $y[$i - 1] -> copy();
$y[$i]{_m} = $LIB -> _add($LIB -> _copy($y[$i - 1]{_m}),
$y[$i - 2]{_m});
}
# If negative, insert sign as appropriate.
if ($x -> is_neg()) {
for (my $i = 2 ; $i <= $#y ; $i += 2) {
$y[$i]{sign} = '-';
}
}
# The last element in the array is the invocand.
$x->{sign} = $y[-1]{sign};
$x->{_m} = $y[-1]{_m};
$x->{_es} = $y[-1]{_es};
$x->{_e} = $y[-1]{_e};
$y[-1] = $x;
}
for (@y) {
$_ -> bnorm();
$_ -> round(@r);
}
return @y;
}
# Scalar context.
else {
return $x if $x -> is_inf('+');
return $x -> bnan() if $x -> is_nan() || $x -> is_inf('-');
if ($x -> is_int()) {
$x->{sign} = $x -> is_neg() && $x -> is_even() ? '-' : '+';
$x->{_m} = $LIB -> _lsft($x->{_m}, $x -> {_e}, 10);
$x->{_e} = $LIB -> _zero();
$x->{_m} = $LIB -> _fib($x->{_m});
$x -> bnorm();
}
return $x -> round(@r);
}
}
sub blucas {
# compute Lucas number(s)
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
croak("blucas() requires a newer version of the $LIB library.")
unless $LIB -> can('_lucas');
# Don't modify constant (read-only) objects.
return $x if $x -> modify('blucas');
# List context.
if (wantarray) {
croak("blucas() can't return an infinitely long list of numbers")
if $x -> is_inf();
return if $x -> is_nan() || !$x -> is_int();
# The following places a limit on how large $x can be. Should this
# limit be removed? XXX
my $n = $x -> numify();
my @y;
{
$y[0] = $x -> copy() -> babs();
$y[0]{_m} = $LIB -> _two();
$y[0]{_e} = $LIB -> _zero();
last if $n == 0;
$y[1] = $y[0] -> copy();
$y[1]{_m} = $LIB -> _one();
$y[1]{_e} = $LIB -> _zero();
last if $n == 1;
for (my $i = 2 ; $i <= abs($n) ; $i++) {
$y[$i] = $y[$i - 1] -> copy();
$y[$i]{_m} = $LIB -> _add($LIB -> _copy($y[$i - 1]{_m}),
$y[$i - 2]{_m});
}
# If negative, insert sign as appropriate.
if ($x -> is_neg()) {
for (my $i = 2 ; $i <= $#y ; $i += 2) {
$y[$i]{sign} = '-';
}
}
# The last element in the array is the invocand.
$x->{sign} = $y[-1]{sign};
$x->{_m} = $y[-1]{_m};
$x->{_es} = $y[-1]{_es};
$x->{_e} = $y[-1]{_e};
$y[-1] = $x;
}
for (@y) {
$_ -> bnorm();
$_ -> round(@r);
}
return @y;
}
# Scalar context.
else {
return $x if $x -> is_inf('+');
return $x -> bnan() if $x -> is_nan() || $x -> is_inf('-');
if ($x -> is_int()) {
$x->{sign} = $x -> is_neg() && $x -> is_even() ? '-' : '+';
$x->{_m} = $LIB -> _lsft($x->{_m}, $x -> {_e}, 10);
$x->{_e} = $LIB -> _zero();
$x->{_m} = $LIB -> _lucas($x->{_m});
$x -> bnorm();
}
return $x -> round(@r);
}
}
sub blsft {
# shift left by $y in base $b, i.e., multiply by $b ** $y
# set up parameters
my ($class, $x, $y, $b, @r)
= ref($_[0]) && ref($_[0]) eq ref($_[1]) && ref($_[1]) eq ref($_[2])
? (ref($_[0]), @_)
: objectify(2, @_);
# Don't modify constant (read-only) objects.
return $x if $x -> modify('blsft');
return $x -> bnan(@r) if $x -> is_nan() || $y -> is_nan();
$b = 2 if !defined $b;
$b = $class -> new($b)
unless defined(blessed($b)) && $b -> isa(__PACKAGE__);
return $x -> bnan(@r) if $b -> is_nan();
# There needs to be more checking for special cases here. Fixme!
# shift by a negative amount?
return $x -> brsft($y -> copy() -> babs(), $b) if $y -> {sign} =~ /^-/;
$x = $x -> bmul($b -> bpow($y), $r[0], $r[1], $r[2], $y);
$x -> round(@r);
$x -> _dng() if ($x -> is_int() ||
$x -> is_inf() ||
$x -> is_nan());
return $x;
}
sub brsft {
# shift right by $y in base $b, i.e., divide by $b ** $y
# set up parameters
my ($class, $x, $y, $b, @r)
= ref($_[0]) && ref($_[0]) eq ref($_[1]) && ref($_[1]) eq ref($_[2])
? (ref($_[0]), @_)
: objectify(2, @_);
# Don't modify constant (read-only) objects.
return $x if $x -> modify('brsft');
return $x -> bnan(@r) if $x -> is_nan() || $y -> is_nan();
# There needs to be more checking for special cases here. Fixme!
$b = 2 if !defined $b;
$b = $class -> new($b)
unless defined(blessed($b)) && $b -> isa(__PACKAGE__);
return $x -> bnan(@r) if $b -> is_nan();
# shift by a negative amount?
return $x -> blsft($y -> copy() -> babs(), $b) if $y -> {sign} =~ /^-/;
# call bdiv()
$x = $x -> bdiv($b -> bpow($y), $r[0], $r[1], $r[2], $y);
$x -> round(@r);
$x -> _dng() if ($x -> is_int() ||
$x -> is_inf() ||
$x -> is_nan());
return $x;
}
###############################################################################
# Bitwise methods
###############################################################################
# Bitwise left shift.
sub bblsft {
# We don't call objectify(), because the bitwise methods should not
# upgrade, even when upgrading is enabled.
my ($class, $x, $y, @r) = ref($_[0]) ? (ref($_[0]), @_) : @_;
# Don't modify constant (read-only) objects.
return $x if $x -> modify('bblsft');
# Let Math::BigInt do the job.
my $xint = Math::BigInt -> bblsft($x, $y, @r);
# Temporarily disable downgrading.
my $dng = $class -> downgrade();
$class -> downgrade(undef);
# convert to our class without downgrading.
my $xflt = $class -> new($xint);
# Reset downgrading.
$class -> downgrade($dng);
# If we are called as a class method, the first operand might not be an
# object of this class, so check.
if (defined(blessed($x)) && $x -> isa(__PACKAGE__)) {
$x -> {sign} = $xflt -> {sign};
$x -> {_m} = $xflt -> {_m};
$x -> {_es} = $xflt -> {_es};
$x -> {_e} = $xflt -> {_e};
} else {
$x = $xflt;
}
# Now we might downgrade.
$x -> round(@r);
$x -> _dng();
return $x;
}
# Bitwise right shift.
sub bbrsft {
# We don't call objectify(), because the bitwise methods should not
# upgrade, even when upgrading is enabled.
my ($class, $x, $y, @r) = ref($_[0]) ? (ref($_[0]), @_) : @_;
# Don't modify constant (read-only) objects.
return $x if $x -> modify('bbrsft');
# Let Math::BigInt do the job.
my $xint = Math::BigInt -> bbrsft($x, $y, @r);
# Temporarily disable downgrading.
my $dng = $class -> downgrade();
$class -> downgrade(undef);
# Convert to our class without downgrading.
my $xflt = $class -> new($xint);
# Reset downgrading.
$class -> downgrade($dng);
# If we are called as a class method, the first operand might not be an
# object of this class, so check.
if (defined(blessed($x)) && $x -> isa(__PACKAGE__)) {
$x -> {sign} = $xflt -> {sign};
$x -> {_m} = $xflt -> {_m};
$x -> {_es} = $xflt -> {_es};
$x -> {_e} = $xflt -> {_e};
} else {
$x = $xflt;
}
# Now we might downgrade.
$x -> round(@r);
$x -> _dng();
return $x;
}
sub band {
my ($class, $x, $y, @r) = ref($_[0]) && ref($_[0]) eq ref($_[1])
? (ref($_[0]), @_)
: objectify(2, @_);
# Don't modify constant (read-only) objects.
return if $x -> modify('band');
# If $x and/or $y is Inf or NaN, return NaN.
return $x -> bnan(@r) if ($x -> is_nan() || $x -> is_inf() ||
$y -> is_nan() || $y -> is_inf());
# This should be implemented without converting to Math::BigInt. XXX
my $xint = $x -> as_int(); # to Math::BigInt
my $yint = $y -> as_int(); # to Math::BigInt
$xint -> band($yint);
$xint -> round(@r);
my $xflt = $xint -> as_float();
$x -> {sign} = $xflt -> {sign};
$x -> {_m} = $xflt -> {_m};
$x -> {_es} = $xflt -> {_es};
$x -> {_e} = $xflt -> {_e};
return $x -> _dng();
return $x;
}
sub bior {
my ($class, $x, $y, @r) = ref($_[0]) && ref($_[0]) eq ref($_[1])
? (ref($_[0]), @_)
: objectify(2, @_);
# Don't modify constant (read-only) objects.
return if $x -> modify('bior');
# If $x and/or $y is Inf or NaN, return NaN.
return $x -> bnan(@r) if ($x -> is_nan() || $x -> is_inf() ||
$y -> is_nan() || $y -> is_inf());
# This should be implemented without converting to Math::BigInt. XXX
my $xint = $x -> as_int(); # to Math::BigInt
my $yint = $y -> as_int(); # to Math::BigInt
$xint -> bior($yint);
$xint -> round(@r);
my $xflt = $xint -> as_float();
$x -> {sign} = $xflt -> {sign};
$x -> {_m} = $xflt -> {_m};
$x -> {_es} = $xflt -> {_es};
$x -> {_e} = $xflt -> {_e};
return $x -> _dng();
return $x;
}
sub bxor {
my ($class, $x, $y, @r) = ref($_[0]) && ref($_[0]) eq ref($_[1])
? (ref($_[0]), @_)
: objectify(2, @_);
# Don't modify constant (read-only) objects.
return if $x -> modify('bxor');
# If $x and/or $y is Inf or NaN, return NaN.
return $x -> bnan(@r) if ($x -> is_nan() || $x -> is_inf() ||
$y -> is_nan() || $y -> is_inf());
# This should be implemented without converting to Math::BigInt. XXX
my $xint = $x -> as_int(); # to Math::BigInt
my $yint = $y -> as_int(); # to Math::BigInt
$xint -> bxor($yint);
$xint -> round(@r);
my $xflt = $xint -> as_float();
$x -> {sign} = $xflt -> {sign};
$x -> {_m} = $xflt -> {_m};
$x -> {_es} = $xflt -> {_es};
$x -> {_e} = $xflt -> {_e};
return $x -> _dng();
return $x;
}
sub bnot {
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
# Don't modify constant (read-only) objects.
return if $x -> modify('bnot');
return $x -> bnan(@r) if $x -> is_nan();
# This should be implemented without converting to Math::BigInt. XXX
my $xint = $x -> as_int(); # to Math::BigInt
$xint -> bnot();
$xint -> round(@r);
my $xflt = $xint -> as_float();
$x -> {sign} = $xflt -> {sign};
$x -> {_m} = $xflt -> {_m};
$x -> {_es} = $xflt -> {_es};
$x -> {_e} = $xflt -> {_e};
return $x -> _dng();
return $x;
}
###############################################################################
# Rounding methods
###############################################################################
sub bround {
# accuracy: preserve $N digits, and overwrite the rest with 0's
my ($class, $x, @a) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
if (($a[0] || 0) < 0) {
croak('bround() needs positive accuracy');
}
# Don't modify constant (read-only) objects.
return $x if $x -> modify('bround');
my ($scale, $mode) = $x->_scale_a(@a);
if (!defined $scale) { # no-op
$x -> _dng() if ($x -> is_int() ||
$x -> is_inf() ||
$x -> is_nan());
return $x;
}
# Scale is now either $x->{accuracy}, $accuracy, or the input argument.
# Test whether $x already has lower accuracy, do nothing in this case but
# do round if the accuracy is the same, since a math operation might want
# to round a number with A=5 to 5 digits afterwards again
if (defined $x->{accuracy} && $x->{accuracy} < $scale) {
$x -> _dng() if ($x -> is_int() ||
$x -> is_inf() ||
$x -> is_nan());
return $x;
}
# scale < 0 makes no sense
# scale == 0 => keep all digits
# never round a +-inf, NaN
if ($scale <= 0 || $x->{sign} !~ /^[+-]$/) {
$x -> _dng() if ($x -> is_int() ||
$x -> is_inf() ||
$x -> is_nan());
return $x;
}
# 1: never round a 0
# 2: if we should keep more digits than the mantissa has, do nothing
if ($x -> is_zero() || $LIB->_len($x->{_m}) <= $scale) {
$x->{accuracy} = $scale if !defined $x->{accuracy} || $x->{accuracy} > $scale;
$x -> _dng() if $x -> is_int();
return $x;
}
# pass sign to bround for '+inf' and '-inf' rounding modes
my $m = bless { sign => $x->{sign}, value => $x->{_m} }, 'Math::BigInt';
$m = $m -> bround($scale, $mode); # round mantissa
$x->{_m} = $m->{value}; # get our mantissa back
$x->{accuracy} = $scale; # remember rounding
$x->{precision} = undef; # and clear P
# bnorm() downgrades if necessary, so no need to check whether to
# downgrade.
$x -> bnorm(); # del trailing zeros gen. by bround()
}
sub bfround {
# precision: round to the $Nth digit left (+$n) or right (-$n) from the '.'
# $n == 0 means round to integer
# expects and returns normalized numbers!
my ($class, $x, @p) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
# Don't modify constant (read-only) objects.
return $x if $x -> modify('bfround'); # no-op
my ($scale, $mode) = $x->_scale_p(@p);
if (!defined $scale) {
$x -> _dng() if ($x -> is_int() ||
$x -> is_inf() ||
$x -> is_nan());
return $x;
}
# never round a 0, +-inf, NaN
if ($x -> is_zero()) {
$x->{precision} = $scale if !defined $x->{precision} || $x->{precision} < $scale; # -3 < -2
$x -> _dng() if ($x -> is_int() ||
$x -> is_inf() ||
$x -> is_nan());
return $x;
}
if ($x->{sign} !~ /^[+-]$/) {
$x -> _dng() if ($x -> is_int() ||
$x -> is_inf() ||
$x -> is_nan());
return $x;
}
# don't round if x already has lower precision
if (defined $x->{precision} && $x->{precision} < 0 && $scale < $x->{precision}) {
$x -> _dng() if ($x -> is_int() ||
$x -> is_inf() ||
$x -> is_nan());
return $x;
}
$x->{precision} = $scale; # remember round in any case
$x->{accuracy} = undef; # and clear A
if ($scale < 0) {
# round right from the '.'
if ($x->{_es} eq '+') { # e >= 0 => nothing to round
$x -> _dng() if ($x -> is_int() ||
$x -> is_inf() ||
$x -> is_nan());
return $x;
}
$scale = -$scale; # positive for simplicity
my $len = $LIB->_len($x->{_m}); # length of mantissa
# the following poses a restriction on _e, but if _e is bigger than a
# scalar, you got other problems (memory etc) anyway
my $dad = -(0+ ($x->{_es}.$LIB->_num($x->{_e}))); # digits after dot
my $zad = 0; # zeros after dot
$zad = $dad - $len if (-$dad < -$len); # for 0.00..00xxx style
# print "scale $scale dad $dad zad $zad len $len\n";
# number bsstr len zad dad
# 0.123 123e-3 3 0 3
# 0.0123 123e-4 3 1 4
# 0.001 1e-3 1 2 3
# 1.23 123e-2 3 0 2
# 1.2345 12345e-4 5 0 4
# do not round after/right of the $dad
if ($scale > $dad) { # 0.123, scale >= 3 => exit
$x -> _dng() if ($x -> is_int() ||
$x -> is_inf() ||
$x -> is_nan());
return $x;
}
# round to zero if rounding inside the $zad, but not for last zero like:
# 0.0065, scale -2, round last '0' with following '65' (scale == zad
# case)
if ($scale < $zad) {
$x -> _dng() if ($x -> is_int() ||
$x -> is_inf() ||
$x -> is_nan());
return $x -> bzero();
}
if ($scale == $zad) { # for 0.006, scale -3 and trunc
$scale = -$len;
} else {
# adjust round-point to be inside mantissa
if ($zad != 0) {
$scale = $scale-$zad;
} else {
my $dbd = $len - $dad;
$dbd = 0 if $dbd < 0; # digits before dot
$scale = $dbd+$scale;
}
}
} else {
# round left from the '.'
# 123 => 100 means length(123) = 3 - $scale (2) => 1
my $dbt = $LIB->_len($x->{_m});
# digits before dot
my $dbd = $dbt + ($x->{_es} . $LIB->_num($x->{_e}));
# should be the same, so treat it as this
$scale = 1 if $scale == 0;
# shortcut if already integer
if ($scale == 1 && $dbt <= $dbd) {
$x -> _dng() if ($x -> is_int() ||
$x -> is_inf() ||
$x -> is_nan());
return $x;
}
# maximum digits before dot
++$dbd;
if ($scale > $dbd) {
# not enough digits before dot, so round to zero
return $x -> bzero;
} elsif ($scale == $dbd) {
# maximum
$scale = -$dbt;
} else {
$scale = $dbd - $scale;
}
}
# pass sign to bround for rounding modes '+inf' and '-inf'
my $m = bless { sign => $x->{sign}, value => $x->{_m} }, 'Math::BigInt';
$m = $m -> bround($scale, $mode);
$x->{_m} = $m->{value}; # get our mantissa back
# bnorm() downgrades if necessary, so no need to check whether to
# downgrade.
$x -> bnorm();
}
sub bfloor {
# round towards minus infinity
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
# Don't modify constant (read-only) objects.
return $x if $x -> modify('bfloor');
return $x -> bnan(@r) if $x -> is_nan();
if ($x -> is_finite()) {
# if $x has digits after dot, remove them
if ($x->{_es} eq '-') {
$x->{_m} = $LIB->_rsft($x->{_m}, $x->{_e}, 10);
$x->{_e} = $LIB->_zero();
$x->{_es} = '+';
# increment if negative
$x->{_m} = $LIB->_inc($x->{_m}) if $x->{sign} eq '-';
}
}
$x -> round(@r);
$x -> _dng();
return $x;
}
sub bceil {
# round towards plus infinity
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
# Don't modify constant (read-only) objects.
return $x if $x -> modify('bceil');
return $x -> bnan(@r) if $x -> is_nan();
if ($x -> is_finite()) {
# if $x has digits after dot, remove them
if ($x->{_es} eq '-') {
$x->{_m} = $LIB->_rsft($x->{_m}, $x->{_e}, 10);
$x->{_e} = $LIB->_zero();
$x->{_es} = '+';
if ($x->{sign} eq '+') {
$x->{_m} = $LIB->_inc($x->{_m}); # increment if positive
} else {
$x->{sign} = '+' if $LIB->_is_zero($x->{_m}); # avoid -0
}
}
}
$x -> round(@r);
$x -> _dng();
return $x;
}
sub bint {
# round towards zero
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
# Don't modify constant (read-only) objects.
return $x if $x -> modify('bint');
return $x -> bnan(@r) if $x -> is_nan();
if ($x -> is_finite()) {
# if $x has digits after the decimal point
if ($x->{_es} eq '-') {
$x->{_m} = $LIB->_rsft($x->{_m}, $x->{_e}, 10); # remove frac part
$x->{_e} = $LIB->_zero(); # truncate/normalize
$x->{_es} = '+'; # abs e
$x->{sign} = '+' if $LIB->_is_zero($x->{_m}); # avoid -0
}
}
$x -> round(@r);
$x -> _dng();
return $x;
}
###############################################################################
# Other mathematical methods
###############################################################################
sub bgcd {
# GCD -- Euclid's algorithm, variant C (Knuth Vol 3, pg 341 ff)
# Class::method(...) -> Class->method(...)
unless (@_ && (defined(blessed($_[0])) && $_[0] -> isa(__PACKAGE__) ||
($_[0] =~ /^[a-z]\w*(?:::[a-z]\w*)*$/i &&
$_[0] !~ /^(inf|nan)/i)))
{
#carp "Using ", (caller(0))[3], "() as a function is deprecated;",
# " use is as a method instead";
unshift @_, __PACKAGE__;
}
my ($class, @args) = objectify(0, @_);
# Pre-process list of operands.
for my $arg (@args) {
return $class -> bnan() unless $arg -> is_finite();
}
# Temporarily disable downgrading.
my $dng = $class -> downgrade();
$class -> downgrade(undef);
my $x = shift @args;
$x = $x -> copy(); # bgcd() and blcm() never modify any operands
while (@args) {
my $y = shift @args;
# greatest common divisor
while (! $y -> is_zero()) {
($x, $y) = ($y -> copy(), $x -> copy() -> bmod($y));
}
last if $x -> is_one();
}
$x -> babs();
# Restore downgrading.
$class -> downgrade($dng);
$x -> _dng() if $x -> is_int();
return $x;
}
sub blcm {
# Least Common Multiple
# Class::method(...) -> Class->method(...)
unless (@_ && (defined(blessed($_[0])) && $_[0] -> isa(__PACKAGE__) ||
($_[0] =~ /^[a-z]\w*(?:::[a-z]\w*)*$/i &&
$_[0] !~ /^(inf|nan)/i)))
{
#carp "Using ", (caller(0))[3], "() as a function is deprecated;",
# " use is as a method instead";
unshift @_, __PACKAGE__;
}
my ($class, @args) = objectify(0, @_);
# Pre-process list of operands.
for my $arg (@args) {
return $class -> bnan() unless $arg -> is_finite();
}
for my $arg (@args) {
return $class -> bzero() if $arg -> is_zero();
}
my $x = shift @args;
$x = $x -> copy(); # bgcd() and blcm() never modify any operands
while (@args) {
my $y = shift @args;
my $gcd = $x -> copy() -> bgcd($y);
$x -> bdiv($gcd) -> bmul($y);
}
$x -> babs(); # might downgrade
return $x;
}
###############################################################################
# Object property methods
###############################################################################
sub length {
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;
return 1 if $LIB->_is_zero($x->{_m});
my $len = $LIB->_len($x->{_m});
$len += $LIB->_num($x->{_e}) if $x->{_es} eq '+';
if (wantarray()) {
my $t = 0;
$t = $LIB->_num($x->{_e}) if $x->{_es} eq '-';
return $len, $t;
}
$len;
}
sub mantissa {
# return a copy of the mantissa
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
# The following line causes a lot of noise in the test suits for
# the Math-BigRat and bignum distributions. Fixme!
#carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;
return $x -> bnan(@r) if $x -> is_nan();
if ($x->{sign} !~ /^[+-]$/) {
my $s = $x->{sign};
$s =~ s/^\+//;
return Math::BigInt -> new($s, undef, undef); # -inf, +inf => +inf
}
my $m = Math::BigInt -> new($LIB->_str($x->{_m}), undef, undef);
$m = $m -> bneg() if $x->{sign} eq '-';
$m;
}
sub exponent {
# return a copy of the exponent
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
# The following line causes a lot of noise in the test suits for
# the Math-BigRat and bignum distributions. Fixme!
#carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;
return $x -> bnan(@r) if $x -> is_nan();
if ($x->{sign} !~ /^[+-]$/) {
my $s = $x->{sign};
$s =~ s/^[+-]//;
return Math::BigInt -> new($s, undef, undef); # -inf, +inf => +inf
}
Math::BigInt -> new($x->{_es} . $LIB->_str($x->{_e}), undef, undef);
}
sub parts {
# return a copy of both the exponent and the mantissa
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;
if ($x->{sign} !~ /^[+-]$/) {
my $s = $x->{sign};
$s =~ s/^\+//;
my $se = $s;
$se =~ s/^-//;
# +inf => inf and -inf, +inf => inf
return $class -> new($s), $class -> new($se);
}
my $m = Math::BigInt -> bzero();
$m->{value} = $LIB->_copy($x->{_m});
$m = $m -> bneg() if $x->{sign} eq '-';
($m, Math::BigInt -> new($x->{_es} . $LIB->_num($x->{_e})));
}
# Parts used for scientific notation with significand/mantissa and exponent as
# integers. E.g., "12345.6789" is returned as "123456789" (mantissa) and "-4"
# (exponent).
sub sparts {
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;
# Not-a-number.
if ($x -> is_nan()) {
my $mant = $class -> bnan(); # mantissa
return $mant unless wantarray; # scalar context
my $expo = $class -> bnan(); # exponent
return $mant, $expo; # list context
}
# Infinity.
if ($x -> is_inf()) {
my $mant = $class -> binf($x->{sign}); # mantissa
return $mant unless wantarray; # scalar context
my $expo = $class -> binf('+'); # exponent
return $mant, $expo; # list context
}
# Finite number.
my $mant = $class -> new($x);
$mant->{_es} = '+';
$mant->{_e} = $LIB->_zero();
$mant -> _dng();
return $mant unless wantarray;
my $expo = $class -> new($x -> {_es} . $LIB->_str($x -> {_e}));
$expo -> _dng();
return $mant, $expo;
}
# Parts used for normalized notation with significand/mantissa as either 0 or a
# number in the semi-open interval [1,10). E.g., "12345.6789" is returned as
# "1.23456789" and "4".
sub nparts {
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;
# Not-a-number and Infinity.
return $x -> sparts() if $x -> is_nan() || $x -> is_inf();
# Finite number.
my ($mant, $expo) = $x -> sparts();
if ($mant -> bcmp(0)) {
my ($ndigtot, $ndigfrac) = $mant -> length();
my $expo10adj = $ndigtot - $ndigfrac - 1;
if ($expo10adj > 0) { # if mantissa is not an integer
$mant = $mant -> brsft($expo10adj, 10);
return $mant unless wantarray;
$expo = $expo -> badd($expo10adj);
return $mant, $expo;
}
}
return $mant unless wantarray;
return $mant, $expo;
}
# Parts used for engineering notation with significand/mantissa as either 0 or
# a number in the semi-open interval [1,1000) and the exponent is a multiple of
# 3. E.g., "12345.6789" is returned as "12.3456789" and "3".
sub eparts {
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;
# Not-a-number and Infinity.
return $x -> sparts() if $x -> is_nan() || $x -> is_inf();
# Finite number.
my ($mant, $expo) = $x -> nparts();
my $c = $expo -> copy() -> bmod(3);
$mant = $mant -> blsft($c, 10);
return $mant unless wantarray;
$expo = $expo -> bsub($c);
return $mant, $expo;
}
# Parts used for decimal notation, e.g., "12345.6789" is returned as "12345"
# (integer part) and "0.6789" (fraction part).
sub dparts {
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;
# Not-a-number.
if ($x -> is_nan()) {
my $int = $class -> bnan();
return $int unless wantarray;
my $frc = $class -> bzero(); # or NaN?
return $int, $frc;
}
# Infinity.
if ($x -> is_inf()) {
my $int = $class -> binf($x->{sign});
return $int unless wantarray;
my $frc = $class -> bzero();
return $int, $frc;
}
# Finite number.
my $int = $x -> copy();
my $frc;
# If the input is an integer.
if ($int->{_es} eq '+') {
$frc = $class -> bzero();
}
# If the input has a fraction part
else {
$int->{_m} = $LIB -> _rsft($int->{_m}, $int->{_e}, 10);
$int->{_e} = $LIB -> _zero();
$int->{_es} = '+';
$int->{sign} = '+' if $LIB->_is_zero($int->{_m}); # avoid -0
return $int unless wantarray;
$frc = $x -> copy() -> bsub($int);
return $int, $frc;
}
$int -> _dng();
return $int unless wantarray;
return $int, $frc;
}
# Fractional parts with the numerator and denominator as integers. E.g.,
# "123.4375" is returned as "1975" and "16".
sub fparts {
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;
# NaN => NaN/NaN
if ($x -> is_nan()) {
return $class -> bnan() unless wantarray;
return $class -> bnan(), $class -> bnan();
}
# ±Inf => ±Inf/1
if ($x -> is_inf()) {
my $numer = $class -> binf($x->{sign});
return $numer unless wantarray;
my $denom = $class -> bone();
return $numer, $denom;
}
# Finite number.
# If we get here, we know that the output is an integer.
$class = $downgrade if $class -> downgrade();
my @flt_parts = ($x->{sign}, $x->{_m}, $x->{_es}, $x->{_e});
my @rat_parts = $class -> _flt_lib_parts_to_rat_lib_parts(@flt_parts);
my $num = $class -> new($LIB -> _str($rat_parts[1]));
my $den = $class -> new($LIB -> _str($rat_parts[2]));
$num = $num -> bneg() if $rat_parts[0] eq "-";
return $num unless wantarray;
return $num, $den;
}
# Given "123.4375", returns "1975", since "123.4375" is "1975/16".
sub numerator {
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;
return $class -> bnan() if $x -> is_nan();
return $class -> binf($x -> sign()) if $x -> is_inf();
return $class -> bzero() if $x -> is_zero();
# If we get here, we know that the output is an integer.
$class = $downgrade if $class -> downgrade();
if ($x -> {_es} eq '-') { # exponent < 0
my $numer_lib = $LIB -> _copy($x -> {_m});
my $denom_lib = $LIB -> _1ex($x -> {_e});
my $gcd_lib = $LIB -> _gcd($LIB -> _copy($numer_lib), $denom_lib);
$numer_lib = $LIB -> _div($numer_lib, $gcd_lib);
return $class -> new($x -> {sign} . $LIB -> _str($numer_lib));
}
elsif (! $LIB -> _is_zero($x -> {_e})) { # exponent > 0
my $numer_lib = $LIB -> _copy($x -> {_m});
$numer_lib = $LIB -> _lsft($numer_lib, $x -> {_e}, 10);
return $class -> new($x -> {sign} . $LIB -> _str($numer_lib));
}
else { # exponent = 0
return $class -> new($x -> {sign} . $LIB -> _str($x -> {_m}));
}
}
# Given "123.4375", returns "16", since "123.4375" is "1975/16".
sub denominator {
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;
return $class -> bnan() if $x -> is_nan();
# If we get here, we know that the output is an integer.
$class = $downgrade if $class -> downgrade();
if ($x -> {_es} eq '-') { # exponent < 0
my $numer_lib = $LIB -> _copy($x -> {_m});
my $denom_lib = $LIB -> _1ex($x -> {_e});
my $gcd_lib = $LIB -> _gcd($LIB -> _copy($numer_lib), $denom_lib);
$denom_lib = $LIB -> _div($denom_lib, $gcd_lib);
return $class -> new($LIB -> _str($denom_lib));
}
else { # exponent >= 0
return $class -> bone();
}
}
###############################################################################
# String conversion methods
###############################################################################
sub bstr {
# (ref to BFLOAT or num_str) return num_str
# Convert number from internal format to (non-scientific) string format.
# internal format is always normalized (no leading zeros, "-0" => "+0")
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;
# Inf and NaN
if ($x->{sign} ne '+' && $x->{sign} ne '-') {
return $x->{sign} unless $x -> is_inf("+"); # -inf, NaN
return 'inf'; # +inf
}
# Finite number
my $es = '0';
my $len = 1;
my $cad = 0;
my $dot = '.';
# $x is zero?
my $not_zero = !($x->{sign} eq '+' && $LIB->_is_zero($x->{_m}));
if ($not_zero) {
$es = $LIB->_str($x->{_m});
$len = CORE::length($es);
my $e = $LIB->_num($x->{_e});
$e = -$e if $x->{_es} eq '-';
if ($e < 0) {
$dot = '';
# if _e is bigger than a scalar, the following will blow your memory
if ($e <= -$len) {
my $r = abs($e) - $len;
$es = '0.'. ('0' x $r) . $es;
$cad = -($len+$r);
} else {
substr($es, $e, 0) = '.';
$cad = $LIB->_num($x->{_e});
$cad = -$cad if $x->{_es} eq '-';
}
} elsif ($e > 0) {
# expand with zeros
$es .= '0' x $e;
$len += $e;
$cad = 0;
}
} # if not zero
$es = '-'.$es if $x->{sign} eq '-';
# if set accuracy or precision, pad with zeros on the right side
if ((defined $x->{accuracy}) && ($not_zero)) {
# 123400 => 6, 0.1234 => 4, 0.001234 => 4
my $zeros = $x->{accuracy} - $cad; # cad == 0 => 12340
$zeros = $x->{accuracy} - $len if $cad != $len;
$es .= $dot.'0' x $zeros if $zeros > 0;
} elsif ((($x->{precision} || 0) < 0)) {
# 123400 => 6, 0.1234 => 4, 0.001234 => 6
my $zeros = -$x->{precision} + $cad;
$es .= $dot.'0' x $zeros if $zeros > 0;
}
$es;
}
# Scientific notation with significand/mantissa and exponent as integers, e.g.,
# "12345.6789" is written as "123456789e-4".
sub bsstr {
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
# Inf and NaN
if ($x->{sign} ne '+' && $x->{sign} ne '-') {
return $x->{sign} unless $x -> is_inf("+"); # -inf, NaN
return 'inf'; # +inf
}
# Upgrade?
return $x -> _upg() -> bsstr(@r)
if $class -> upgrade() && !$x -> isa(__PACKAGE__);
# Round according to arguments or global settings, if any.
$x = $x -> copy() -> round(@r);
# Finite number
($x->{sign} eq '-' ? '-' : '') . $LIB->_str($x->{_m})
. 'e' . $x->{_es} . $LIB->_str($x->{_e});
}
# Normalized notation, e.g., "12345.6789" is written as "1.23456789e+4".
sub bnstr {
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
# Inf and NaN
if ($x->{sign} ne '+' && $x->{sign} ne '-') {
return $x->{sign} unless $x -> is_inf("+"); # -inf, NaN
return 'inf'; # +inf
}
# Upgrade?
return $x -> _upg() -> bnstr(@r)
if $class -> upgrade() && !$x -> isa(__PACKAGE__);
# Finite number
my $str = $x->{sign} eq '-' ? '-' : '';
# Round according to arguments or global settings, if any.
$x = $x -> copy() -> round(@r);
# Get the mantissa and the length of the mantissa.
my $mant = $LIB->_str($x->{_m});
my $mantlen = CORE::length($mant);
if ($mantlen == 1) {
# Not decimal point when the mantissa has length one, i.e., return the
# number 2 as the string "2", not "2.".
$str .= $mant . 'e' . $x->{_es} . $LIB->_str($x->{_e});
} else {
# Compute new exponent where the original exponent is adjusted by the
# length of the mantissa minus one (because the decimal point is after
# one digit).
my ($eabs, $esgn) = $LIB -> _sadd($LIB -> _copy($x->{_e}), $x->{_es},
$LIB -> _new($mantlen - 1), "+");
substr $mant, 1, 0, ".";
$str .= $mant . 'e' . $esgn . $LIB->_str($eabs);
}
return $str;
}
# Engineering notation, e.g., "12345.6789" is written as "12.3456789e+3".
sub bestr {
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
# Inf and NaN
if ($x->{sign} ne '+' && $x->{sign} ne '-') {
return $x->{sign} unless $x -> is_inf("+"); # -inf, NaN
return 'inf'; # +inf
}
# Upgrade?
return $x -> _upg() -> bestr(@r)
if $class -> upgrade() && !$x -> isa(__PACKAGE__);
# Round according to arguments or global settings, if any.
$x = $x -> copy() -> round(@r);
# Finite number
my $str = $x->{sign} eq '-' ? '-' : '';
# Get the mantissa, the length of the mantissa, and adjust the exponent by
# the length of the mantissa minus 1 (because the dot is after one digit).
my $mant = $LIB->_str($x->{_m});
my $mantlen = CORE::length($mant);
my ($eabs, $esgn) = $LIB -> _sadd($LIB -> _copy($x->{_e}), $x->{_es},
$LIB -> _new($mantlen - 1), "+");
my $dotpos = 1;
my $mod = $LIB -> _mod($LIB -> _copy($eabs), $LIB -> _new("3"));
unless ($LIB -> _is_zero($mod)) {
if ($esgn eq '+') {
$eabs = $LIB -> _sub($eabs, $mod);
$dotpos += $LIB -> _num($mod);
} else {
my $delta = $LIB -> _sub($LIB -> _new("3"), $mod);
$eabs = $LIB -> _add($eabs, $delta);
$dotpos += $LIB -> _num($delta);
}
}
if ($dotpos < $mantlen) {
substr $mant, $dotpos, 0, ".";
} elsif ($dotpos > $mantlen) {
$mant .= "0" x ($dotpos - $mantlen);
}
$str .= $mant . 'e' . $esgn . $LIB->_str($eabs);
return $str;
}
# Decimal notation, e.g., "12345.6789" (no exponent).
sub bdstr {
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
# Inf and NaN
if ($x->{sign} ne '+' && $x->{sign} ne '-') {
return $x->{sign} unless $x -> is_inf("+"); # -inf, NaN
return 'inf'; # +inf
}
# Upgrade?
return $x -> _upg() -> bdstr(@r)
if $class -> upgrade() && !$x -> isa(__PACKAGE__);
# Round according to arguments or global settings, if any.
$x = $x -> copy() -> round(@r);
# Finite number
my $mant = $LIB->_str($x->{_m});
my $esgn = $x->{_es};
my $eabs = $LIB -> _num($x->{_e});
my $uintmax = ~0;
my $str = $mant;
if ($esgn eq '+') {
croak("The absolute value of the exponent is too large")
if $eabs > $uintmax;
$str .= "0" x $eabs;
} else {
my $mlen = CORE::length($mant);
my $c = $mlen - $eabs;
my $intmax = ($uintmax - 1) / 2;
croak("The absolute value of the exponent is too large")
if (1 - $c) > $intmax;
$str = "0" x (1 - $c) . $str if $c <= 0;
substr($str, -$eabs, 0) = '.';
}
return $x->{sign} eq '-' ? '-' . $str : $str;
}
# Fractional notation, e.g., "123.4375" is written as "1975/16".
sub bfstr {
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_);
carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;
# Inf and NaN
if ($x->{sign} ne '+' && $x->{sign} ne '-') {
return $x->{sign} unless $x -> is_inf("+"); # -inf, NaN
return 'inf'; # +inf
}
# Upgrade?
return $x -> _upg() -> bfstr(@r)
if $class -> upgrade() && !$x -> isa(__PACKAGE__);
# Finite number
my $str = $x->{sign} eq '-' ? '-' : '';
if ($x->{_es} eq '+') {
$str .= $LIB -> _str($x->{_m}) . ("0" x $LIB -> _num($x->{_e}));
} else {
my @flt_parts = ($x->{sign}, $x->{_m}, $x->{_es}, $x->{_e});
my @rat_parts = $class -> _flt_lib_parts_to_rat_lib_parts(@flt_parts);
$str = $LIB -> _str($rat_parts[1]) . "/" . $LIB -> _str($rat_parts[2]);
$str = "-" . $str if $rat_parts[0] eq "-";
}
return $str;
}
sub to_hex {
# return number as hexadecimal string (only for integers defined)
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_);
carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;
# Inf and NaN
if ($x->{sign} ne '+' && $x->{sign} ne '-') {
return $x->{sign} unless $x -> is_inf("+"); # -inf, NaN
return 'inf'; # +inf
}
# Upgrade?
return $x -> _upg() -> to_hex(@r)
if $class -> upgrade() && !$x -> isa(__PACKAGE__);
# Finite number
return '0' if $x -> is_zero();
return $nan if $x->{_es} ne '+'; # how to do 1e-1 in hex?
my $z = $LIB->_copy($x->{_m});
if (! $LIB->_is_zero($x->{_e})) { # > 0
$z = $LIB->_lsft($z, $x->{_e}, 10);
}
my $str = $LIB->_to_hex($z);
return $x->{sign} eq '-' ? "-$str" : $str;
}
sub to_oct {
# return number as octal digit string (only for integers defined)
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_);
carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;
# Inf and NaN
if ($x->{sign} ne '+' && $x->{sign} ne '-') {
return $x->{sign} unless $x -> is_inf("+"); # -inf, NaN
return 'inf'; # +inf
}
# Upgrade?
return $x -> _upg() -> to_oct(@r)
if $class -> upgrade() && !$x -> isa(__PACKAGE__);
# Finite number
return '0' if $x -> is_zero();
return $nan if $x->{_es} ne '+'; # how to do 1e-1 in octal?
my $z = $LIB->_copy($x->{_m});
if (! $LIB->_is_zero($x->{_e})) { # > 0
$z = $LIB->_lsft($z, $x->{_e}, 10);
}
my $str = $LIB->_to_oct($z);
return $x->{sign} eq '-' ? "-$str" : $str;
}
sub to_bin {
# return number as binary digit string (only for integers defined)
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_);
carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;
# Inf and NaN
if ($x->{sign} ne '+' && $x->{sign} ne '-') {
return $x->{sign} unless $x -> is_inf("+"); # -inf, NaN
return 'inf'; # +inf
}
# Upgrade?
return $x -> _upg() -> to_bin(@r)
if $class -> upgrade() && !$x -> isa(__PACKAGE__);
# Finite number
return '0' if $x -> is_zero();
return $nan if $x->{_es} ne '+'; # how to do 1e-1 in binary?
my $z = $LIB->_copy($x->{_m});
if (! $LIB->_is_zero($x->{_e})) { # > 0
$z = $LIB->_lsft($z, $x->{_e}, 10);
}
my $str = $LIB->_to_bin($z);
return $x->{sign} eq '-' ? "-$str" : $str;
}
sub to_bytes {
# return a byte string
my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;
croak("to_bytes() requires a finite, non-negative integer")
if $x -> is_neg() || ! $x -> is_int();
return $x -> _upg() -> to_bytes(@r)
if $class -> upgrade() && !$x -> isa(__PACKAGE__);
croak("to_bytes() requires a newer version of the $LIB library.")
unless $LIB -> can('_to_bytes');
return $LIB->_to_bytes($LIB -> _lsft($x->{_m}, $x->{_e}, 10));
}
sub to_ieee754 {
my ($class, $x, $format, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;
my $enc; # significand encoding (applies only to decimal)
my $k; # storage width in bits
my $b; # base
if ($format =~ /^binary(\d+)\z/) {
$k = $1;
$b = 2;
} elsif ($format =~ /^decimal(\d+)(dpd|bcd)?\z/) {
$k = $1;
$b = 10;
$enc = $2 || 'dpd'; # default is dencely-packed decimals (DPD)
} elsif ($format eq 'half') {
$k = 16;
$b = 2;
} elsif ($format eq 'single') {
$k = 32;
$b = 2;
} elsif ($format eq 'double') {
$k = 64;
$b = 2;
} elsif ($format eq 'quadruple') {
$k = 128;
$b = 2;
} elsif ($format eq 'octuple') {
$k = 256;
$b = 2;
} elsif ($format eq 'sexdecuple') {
$k = 512;
$b = 2;
}
if ($b == 2) {
# Get the parameters for this format.
my $p; # precision (in bits)
my $t; # number of bits in significand
my $w; # number of bits in exponent
if ($k == 16) { # binary16 (half-precision)
$p = 11;
$t = 10;
$w = 5;
} elsif ($k == 32) { # binary32 (single-precision)
$p = 24;
$t = 23;
$w = 8;
} elsif ($k == 64) { # binary64 (double-precision)
$p = 53;
$t = 52;
$w = 11;
} else { # binaryN (quadruple-precition and above)
if ($k < 128 || $k != 32 * sprintf('%.0f', $k / 32)) {
croak "Number of bits must be 16, 32, 64, or >= 128 and",
" a multiple of 32";
}
$p = $k - sprintf('%.0f', 4 * log($k) / log(2)) + 13;
$t = $p - 1;
$w = $k - $t - 1;
}
# The maximum exponent, minimum exponent, and exponent bias.
my $emax = $class -> new(2) -> bpow($w - 1) -> bdec();
my $emin = 1 - $emax;
my $bias = $emax;
# Get numerical sign, exponent, and mantissa/significand for bit
# string.
my $sign = 0;
my $expo;
my $mant;
if ($x -> is_nan()) { # nan
$sign = 1;
$expo = $emax -> copy() -> binc();
$mant = $class -> new(2) -> bpow($t - 1);
} elsif ($x -> is_inf()) { # inf
$sign = 1 if $x -> is_neg();
$expo = $emax -> copy() -> binc();
$mant = $class -> bzero();
} elsif ($x -> is_zero()) { # zero
$expo = $emin -> copy() -> bdec();
$mant = $class -> bzero();
} else { # normal and subnormal
$sign = 1 if $x -> is_neg();
# Now we need to compute the mantissa and exponent in base $b.
my $binv = $class -> new("0.5");
my $b = $class -> new(2);
my $one = $class -> bone();
# We start off by initializing the exponent to zero and the
# mantissa to the input value. Then we increase the mantissa and
# decrease the exponent, or vice versa, until the mantissa is in
# the desired range or we hit one of the limits for the exponent.
$mant = $x -> copy() -> babs();
# We need to find the base 2 exponent. First make an estimate of
# the base 2 exponent, before adjusting it below. We could skip
# this estimation and go straight to the while-loops below, but the
# loops are slow, especially when the final exponent is far from
# zero and even more so if the number of digits is large. This
# initial estimation speeds up the computation dramatically.
#
# log2($m * 10**$e) = log10($m + 10**$e) * log(10)/log(2)
# = (log10($m) + $e) * log(10)/log(2)
# = (log($m)/log(10) + $e) * log(10)/log(2)
my ($m, $e) = $x -> nparts();
my $ms = $m -> numify();
my $es = $e -> numify();
my $expo_est = (log(abs($ms))/log(10) + $es) * log(10)/log(2);
$expo_est = int($expo_est);
# Limit the exponent.
if ($expo_est > $emax) {
$expo_est = $emax;
} elsif ($expo_est < $emin) {
$expo_est = $emin;
}
# Don't multiply by a number raised to a negative exponent. This
# will cause a division, whose result is truncated to some fixed
# number of digits. Instead, multiply by the inverse number raised
# to a positive exponent.
$expo = $class -> new($expo_est);
if ($expo_est > 0) {
$mant = $mant -> bmul($binv -> copy() -> bpow($expo));
} elsif ($expo_est < 0) {
my $expo_abs = $expo -> copy() -> bneg();
$mant = $mant -> bmul($b -> copy() -> bpow($expo_abs));
}
# Final adjustment of the estimate above.
while ($mant >= $b && $expo <= $emax) {
$mant = $mant -> bmul($binv);
$expo = $expo -> binc();
}
while ($mant < $one && $expo >= $emin) {
$mant = $mant -> bmul($b);
$expo = $expo -> bdec();
}
# This is when the magnitude is larger than what can be represented
# in this format. Encode as infinity.
if ($expo > $emax) {
$mant = $class -> bzero();
$expo = $emax -> copy() -> binc();
}
# This is when the magnitude is so small that the number is encoded
# as a subnormal number.
#
# If the magnitude is smaller than that of the smallest subnormal
# number, and rounded downwards, it is encoded as zero. This works
# transparently and does not need to be treated as a special case.
#
# If the number is between the largest subnormal number and the
# smallest normal number, and the value is rounded upwards, the
# value must be encoded as a normal number. This must be treated as
# a special case.
elsif ($expo < $emin) {
# Scale up the mantissa (significand), and round to integer.
my $const = $class -> new($b) -> bpow($t - 1);
$mant = $mant -> bmul($const);
$mant = $mant -> bfround(0);
# If the mantissa overflowed, encode as the smallest normal
# number.
if ($mant == $const -> bmul($b)) {
$mant = $mant -> bzero();
$expo = $expo -> binc();
}
}
# This is when the magnitude is within the range of what can be
# encoded as a normal number.
else {
# Remove implicit leading bit, scale up the mantissa
# (significand) to an integer, and round.
$mant = $mant -> bdec();
my $const = $class -> new($b) -> bpow($t);
$mant = $mant -> bmul($const) -> bfround(0);
# If the mantissa overflowed, encode as the next larger value.
# This works correctly also when the next larger value is
# infinity.
if ($mant == $const) {
$mant = $mant -> bzero();
$expo = $expo -> binc();
}
}
}
$expo = $expo -> badd($bias); # add bias
my $signbit = "$sign";
my $mantbits = $mant -> to_bin();
$mantbits = ("0" x ($t - CORE::length($mantbits))) . $mantbits;
my $expobits = $expo -> to_bin();
$expobits = ("0" x ($w - CORE::length($expobits))) . $expobits;
my $bin = $signbit . $expobits . $mantbits;
return pack "B*", $bin;
}
croak("The format '$format' is not yet supported.");
}
sub as_hex {
# return number as hexadecimal string (only for integers defined)
my (undef, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_);
carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;
return $x -> bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc
return '0x0' if $x -> is_zero();
return $nan if $x->{_es} ne '+'; # how to do 1e-1 in hex?
my $z = $LIB->_copy($x->{_m});
if (! $LIB->_is_zero($x->{_e})) { # > 0
$z = $LIB->_lsft($z, $x->{_e}, 10);
}
my $str = $LIB->_as_hex($z);
return $x->{sign} eq '-' ? "-$str" : $str;
}
sub as_oct {
# return number as octal digit string (only for integers defined)
my (undef, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_);
carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;
return $x -> bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc
return '00' if $x -> is_zero();
return $nan if $x->{_es} ne '+'; # how to do 1e-1 in octal?
my $z = $LIB->_copy($x->{_m});
if (! $LIB->_is_zero($x->{_e})) { # > 0
$z = $LIB->_lsft($z, $x->{_e}, 10);
}
my $str = $LIB->_as_oct($z);
return $x->{sign} eq '-' ? "-$str" : $str;
}
sub as_bin {
# return number as binary digit string (only for integers defined)
my (undef, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_);
carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;
return $x -> bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc
return '0b0' if $x -> is_zero();
return $nan if $x->{_es} ne '+'; # how to do 1e-1 in binary?
my $z = $LIB->_copy($x->{_m});
if (! $LIB->_is_zero($x->{_e})) { # > 0
$z = $LIB->_lsft($z, $x->{_e}, 10);
}
my $str = $LIB->_as_bin($z);
return $x->{sign} eq '-' ? "-$str" : $str;
}
sub numify {
# Make a Perl scalar number from a Math::BigFloat object.
my (undef, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_);
carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;
if ($x -> is_nan()) {
require Math::Complex;
my $inf = $Math::Complex::Inf;
return $inf - $inf;
}
if ($x -> is_inf()) {
require Math::Complex;
my $inf = $Math::Complex::Inf;
return $x -> is_negative() ? -$inf : $inf;
}
# Create a string and let Perl's atoi()/atof() handle the rest.
return 0 + $x -> bnstr();
}
###############################################################################
# Private methods and functions.
###############################################################################
sub import {
my $class = shift;
$IMPORT++; # remember we did import()
my @a; # unrecognized arguments
my @import = ();
while (@_) {
my $param = shift;
# Enable overloading of constants.
if ($param eq ':constant') {
overload::constant
integer => sub {
$class -> new(shift);
},
float => sub {
$class -> new(shift);
},
binary => sub {
# E.g., a literal 0377 shall result in an object whose
# value is decimal 255, but new("0377") returns decimal
# 377.
return $class -> from_oct($_[0]) if $_[0] =~ /^0_*[0-7]/;
$class -> new(shift);
};
next;
}
# Upgrading.
if ($param eq 'upgrade') {
$class -> upgrade(shift);
next;
}
# Downgrading.
if ($param eq 'downgrade') {
$class -> downgrade(shift);
next;
}
# Accuracy.
if ($param eq 'accuracy') {
$class -> accuracy(shift);
next;
}
# Precision.
if ($param eq 'precision') {
$class -> precision(shift);
next;
}
# Rounding mode.
if ($param eq 'round_mode') {
$class -> round_mode(shift);
next;
}
# Fall-back accuracy.
if ($param eq 'div_scale') {
$class -> div_scale(shift);
next;
}
# Backend library.
if ($param =~ /^(lib|try|only)\z/) {
push @import, $param;
push @import, shift() if @_;
next;
}
if ($param eq 'with') {
# alternative class for our private parts()
# XXX: no longer supported
# $LIB = shift() || 'Calc';
# carp "'with' is no longer supported, use 'lib', 'try', or 'only'";
shift;
next;
}
# Unrecognized parameter.
push @a, $param;
}
Math::BigInt -> import(@import);
# find out which library was actually loaded
$LIB = Math::BigInt -> config('lib');
$class -> SUPER::import(@a); # for subclasses
$class -> export_to_level(1, $class, @a) if @a; # need this, too
}
sub _len_to_steps {
# Given D (digits in decimal), compute N so that N! (N factorial) is
# at least D digits long. D should be at least 50.
my $d = shift;
# two constants for the Ramanujan estimate of ln(N!)
my $lg2 = log(2 * 3.14159265) / 2;
my $lg10 = log(10);
# D = 50 => N => 42, so L = 40 and R = 50
my $l = 40;
my $r = $d;
# Otherwise this does not work under -Mbignum and we do not yet have "no
# bignum;" :(
$l = $l -> numify if ref($l);
$r = $r -> numify if ref($r);
$lg2 = $lg2 -> numify if ref($lg2);
$lg10 = $lg10 -> numify if ref($lg10);
# binary search for the right value (could this be written as the reverse
# of lg(n!)?)
while ($r - $l > 1) {
my $n = int(($r - $l) / 2) + $l;
my $ramanujan
= int(($n * log($n) - $n + log($n * (1 + 4*$n*(1+2*$n))) / 6 + $lg2)
/ $lg10);
$ramanujan > $d ? $r = $n : $l = $n;
}
$l;
}
sub _log {
# internal log function to calculate ln() based on Taylor series.
# Modifies $x in place.
my ($x, $scale) = @_;
my $class = ref $x;
# in case of $x == 1, result is 0
return $x -> bzero() if $x -> is_one();
# XXX TODO: rewrite this in a similar manner to bexp()
# http://www.efunda.com/math/taylor_series/logarithmic.cfm?search_string=log
# u = x-1, v = x+1
# _ _
# Taylor: | u 1 u^3 1 u^5 |
# ln (x) = 2 | --- + - * --- + - * --- + ... | x > 0
# |_ v 3 v^3 5 v^5 _|
# This takes much more steps to calculate the result and is thus not used
# u = x-1
# _ _
# Taylor: | u 1 u^2 1 u^3 |
# ln (x) = 2 | --- + - * --- + - * --- + ... | x > 1/2
# |_ x 2 x^2 3 x^3 _|
# scale used in intermediate computations
my $scaleup = $scale + 4;
my ($v, $u, $numer, $denom, $factor, $f);
$v = $x -> copy();
$v = $v -> binc(); # v = x+1
$x = $x -> bdec();
$u = $x -> copy(); # u = x-1; x = x-1
$x = $x -> bdiv($v, $scaleup); # first term: u/v
$numer = $u -> copy(); # numerator
$denom = $v -> copy(); # denominator
$u = $u -> bmul($u); # u^2
$v = $v -> bmul($v); # v^2
$numer = $numer -> bmul($u); # u^3
$denom = $denom -> bmul($v); # v^3
$factor = $class -> new(3);
$f = $class -> new(2);
while (1) {
my $next = $numer -> copy() -> bround($scaleup)
-> bdiv($denom -> copy() -> bmul($factor) -> bround($scaleup), $scaleup);
$next->{accuracy} = undef;
$next->{precision} = undef;
my $x_prev = $x -> copy();
$x = $x -> badd($next);
last if $x -> bacmp($x_prev) == 0;
# calculate things for the next term
$numer = $numer -> bmul($u);
$denom = $denom -> bmul($v);
$factor = $factor -> badd($f);
}
$x = $x -> bmul($f); # $x *= 2
$x = $x -> bround($scale);
}
sub _log_10 {
# Internal log function based on reducing input to the range of 0.1 .. 9.99
# and then "correcting" the result to the proper one. Modifies $x in place.
my ($x, $scale) = @_;
my $class = ref $x;
# Taking blog() from numbers greater than 10 takes a *very long* time, so
# we break the computation down into parts based on the observation that:
# blog(X*Y) = blog(X) + blog(Y)
# We set Y here to multiples of 10 so that $x becomes below 1 - the smaller
# $x is the faster it gets. Since 2*$x takes about 10 times as long, we
# make it faster by about a factor of 100 by dividing $x by 10.
# The same observation is valid for numbers smaller than 0.1, e.g.
# computing log(1) is fastest, and the further away we get from 1, the
# longer it takes. So we also 'break' this down by multiplying $x with 10
# and subtract the log(10) afterwards to get the correct result.
# To get $x even closer to 1, we also divide by 2 and then use log(2) to
# correct for this. For instance if $x is 2.4, we use the formula:
# blog(2.4 * 2) == blog(1.2) + blog(2)
# and thus calculate only blog(1.2) and blog(2), which is faster in total
# than calculating blog(2.4).
# In addition, the values for blog(2) and blog(10) are cached.
# Calculate the number of digits before the dot, i.e., 1 + floor(log10(x)):
# x = 123 => dbd = 3
# x = 1.23 => dbd = 1
# x = 0.0123 => dbd = -1
# x = 0.000123 => dbd = -3
# etc.
my $dbd = $LIB->_num($x->{_e});
$dbd = -$dbd if $x->{_es} eq '-';
$dbd += $LIB->_len($x->{_m});
# more than one digit (e.g. at least 10), but *not* exactly 10 to avoid
# infinite recursion
my $calc = 1; # do some calculation?
# No upgrading or downgrading in the intermediate computations.
my $upg = $class -> upgrade();
my $dng = $class -> downgrade();
$class -> upgrade(undef);
$class -> downgrade(undef);
# disable the shortcut for 10, since we need log(10) and this would recurse
# infinitely deep
if ($x->{_es} eq '+' && # $x == 10
($LIB->_is_one($x->{_e}) &&
$LIB->_is_one($x->{_m})))
{
$dbd = 0; # disable shortcut
# we can use the cached value in these cases
if ($scale <= $LOG_10_A) {
$x = $x -> bzero();
$x = $x -> badd($LOG_10); # modify $x in place
$calc = 0; # no need to calc, but round
}
# if we can't use the shortcut, we continue normally
} else {
# disable the shortcut for 2, since we maybe have it cached
if (($LIB->_is_zero($x->{_e}) && # $x == 2
$LIB->_is_two($x->{_m})))
{
$dbd = 0; # disable shortcut
# we can use the cached value in these cases
if ($scale <= $LOG_2_A) {
$x = $x -> bzero();
$x = $x -> badd($LOG_2); # modify $x in place
$calc = 0; # no need to calc, but round
}
# if we can't use the shortcut, we continue normally
}
}
# if $x = 0.1, we know the result must be 0-log(10)
if ($calc != 0 &&
($x->{_es} eq '-' && # $x == 0.1
($LIB->_is_one($x->{_e}) &&
$LIB->_is_one($x->{_m}))))
{
$dbd = 0; # disable shortcut
# we can use the cached value in these cases
if ($scale <= $LOG_10_A) {
$x = $x -> bzero();
$x = $x -> bsub($LOG_10);
$calc = 0; # no need to calc, but round
}
}
return $x if $calc == 0; # already have the result
# default: these correction factors are undef and thus not used
my $l_10; # value of ln(10) to A of $scale
my $l_2; # value of ln(2) to A of $scale
my $two = $class -> new(2);
# $x == 2 => 1, $x == 13 => 2, $x == 0.1 => 0, $x == 0.01 => -1
# so don't do this shortcut for 1 or 0
if (($dbd > 1) || ($dbd < 0)) {
# convert our cached value to an object if not already (avoid doing
# this at import() time, since not everybody needs this)
$LOG_10 = $class -> new($LOG_10, undef, undef) unless ref $LOG_10;
# got more than one digit before the dot, or more than one zero after
# the dot, so do:
# log(123) == log(1.23) + log(10) * 2
# log(0.0123) == log(1.23) - log(10) * 2
if ($scale <= $LOG_10_A) {
# use cached value
$l_10 = $LOG_10 -> copy(); # copy for mul
} else {
# else: slower, compute and cache result
# shorten the time to calculate log(10) based on the following:
# log(1.25 * 8) = log(1.25) + log(8)
# = log(1.25) + log(2) + log(2) + log(2)
# first get $l_2 (and possible compute and cache log(2))
$LOG_2 = $class -> new($LOG_2, undef, undef) unless ref $LOG_2;
if ($scale <= $LOG_2_A) {
# use cached value
$l_2 = $LOG_2 -> copy(); # copy() for the mul below
} else {
# else: slower, compute and cache result
$l_2 = $two -> copy();
$l_2 = $l_2->_log($scale); # scale+4, actually
$LOG_2 = $l_2 -> copy(); # cache the result for later
# the copy() is for mul below
$LOG_2_A = $scale;
}
# now calculate log(1.25):
$l_10 = $class -> new('1.25');
$l_10 = $l_10->_log($scale); # scale+4, actually
# log(1.25) + log(2) + log(2) + log(2):
$l_10 = $l_10 -> badd($l_2);
$l_10 = $l_10 -> badd($l_2);
$l_10 = $l_10 -> badd($l_2);
$LOG_10 = $l_10 -> copy(); # cache the result for later
# the copy() is for mul below
$LOG_10_A = $scale;
}
$dbd-- if ($dbd > 1); # 20 => dbd=2, so make it dbd=1
$l_10 = $l_10 -> bmul($class -> new($dbd)); # log(10) * (digits_before_dot-1)
my $dbd_sign = '+';
if ($dbd < 0) {
$dbd = -$dbd;
$dbd_sign = '-';
}
($x->{_e}, $x->{_es}) =
$LIB -> _ssub($x->{_e}, $x->{_es}, $LIB->_new($dbd), $dbd_sign);
}
# Now: 0.1 <= $x < 10 (and possible correction in l_10)
### Since $x in the range 0.5 .. 1.5 is MUCH faster, we do a repeated div
### or mul by 2 (maximum times 3, since x < 10 and x > 0.1)
$HALF = $class -> new($HALF) unless ref($HALF);
my $twos = 0; # default: none (0 times)
while ($x -> bacmp($HALF) <= 0) { # X <= 0.5
$twos--;
$x = $x -> bmul($two);
}
while ($x -> bacmp($two) >= 0) { # X >= 2
$twos++;
$x = $x -> bdiv($two, $scale+4); # keep all digits
}
$x = $x -> bround($scale+4);
# $twos > 0 => did mul 2, < 0 => did div 2 (but we never did both)
# So calculate correction factor based on ln(2):
if ($twos != 0) {
$LOG_2 = $class -> new($LOG_2, undef, undef) unless ref $LOG_2;
if ($scale <= $LOG_2_A) {
# use cached value
$l_2 = $LOG_2 -> copy(); # copy() for the mul below
} else {
# else: slower, compute and cache result
$l_2 = $two -> copy();
$l_2 = $l_2->_log($scale); # scale+4, actually
$LOG_2 = $l_2 -> copy(); # cache the result for later
# the copy() is for mul below
$LOG_2_A = $scale;
}
$l_2 = $l_2 -> bmul($twos); # * -2 => subtract, * 2 => add
} else {
undef $l_2;
}
$x = $x->_log($scale); # need to do the "normal" way
$x = $x -> badd($l_10) if defined $l_10; # correct it by ln(10)
$x = $x -> badd($l_2) if defined $l_2; # and maybe by ln(2)
# Restore globals
$class -> upgrade($upg);
$class -> downgrade($dng);
# all done, $x contains now the result
$x;
}
sub _pow {
# Calculate a power where $y is a non-integer, like 2 ** 0.3
my ($x, $y, @r) = @_;
my $class = ref($x);
# if $y == 0.5, it is sqrt($x)
$HALF = $class -> new($HALF) unless ref($HALF);
return $x -> bsqrt(@r, $y) if $y -> bcmp($HALF) == 0;
# Using:
# a ** x == e ** (x * ln a)
# u = y * ln x
# _ _
# Taylor: | u u^2 u^3 |
# x ** y = 1 + | --- + --- + ----- + ... |
# |_ 1 1*2 1*2*3 _|
# we need to limit the accuracy to protect against overflow
my $fallback = 0;
my ($scale, @params);
($x, @params) = $x->_find_round_parameters(@r);
return $x if $x -> is_nan(); # error in _find_round_parameters?
# no rounding at all, so must use fallback
if (scalar @params == 0) {
# simulate old behaviour
$params[0] = $class -> div_scale(); # and round to it as accuracy
$params[1] = undef; # disable P
$scale = $params[0]+4; # at least four more for proper round
$params[2] = $r[2]; # round mode by caller or undef
$fallback = 1; # to clear a/p afterwards
} else {
# the 4 below is empirical, and there might be cases where it is not
# enough...
$scale = abs($params[0] || $params[1]) + 4; # take whatever is defined
}
# When user set globals, they would interfere with our calculation, so
# disable them and later re-enable them.
my $ab = $class -> accuracy();
my $pb = $class -> precision();
$class -> accuracy(undef);
$class -> precision(undef);
# Disabling upgrading and downgrading is no longer necessary to avoid an
# infinite recursion, but it avoids unnecessary upgrading and downgrading
# in the intermediate computations.
my $upg = $class -> upgrade();
my $dng = $class -> downgrade();
$class -> upgrade(undef);
$class -> downgrade(undef);
# We also need to disable any set A or P on $x (_find_round_parameters took
# them already into account), since these would interfere, too.
$x->{accuracy} = undef;
$x->{precision} = undef;
my ($limit, $v, $u, $below, $factor, $next, $over);
$u = $x -> copy() -> blog(undef, $scale) -> bmul($y);
my $do_invert = ($u->{sign} eq '-');
$u = $u -> bneg() if $do_invert;
$v = $class -> bone(); # 1
$factor = $class -> new(2); # 2
$x = $x -> bone(); # first term: 1
$below = $v -> copy();
$over = $u -> copy();
$limit = $class -> new("1E-". ($scale-1));
while (3 < 5) {
# we calculate the next term, and add it to the last
# when the next term is below our limit, it won't affect the outcome
# anymore, so we stop:
$next = $over -> copy() -> bdiv($below, $scale);
last if $next -> bacmp($limit) <= 0;
$x = $x -> badd($next);
# calculate things for the next term
$over *= $u;
$below *= $factor;
$factor = $factor -> binc();
last if $x->{sign} !~ /^[-+]$/;
}
if ($do_invert) {
my $x_copy = $x -> copy();
$x = $x -> bone -> bdiv($x_copy, $scale);
}
# shortcut to not run through _find_round_parameters again
if (defined $params[0]) {
$x = $x -> bround($params[0], $params[2]); # then round accordingly
} else {
$x = $x -> bfround($params[1], $params[2]); # then round accordingly
}
if ($fallback) {
# clear a/p after round, since user did not request it
$x->{accuracy} = undef;
$x->{precision} = undef;
}
# Restore globals. We need to do it like this, because setting one
# undefines the other.
if (defined $ab) {
$class -> accuracy($ab);
} else {
$class -> precision($pb);
}
$class -> upgrade($upg);
$class -> downgrade($dng);
$x;
}
# These functions are only provided for backwards compabibility so that old
# version of Math::BigRat etc. don't complain about missing them.
sub _e_add {
my ($x, $y, $xs, $ys) = @_;
return $LIB -> _sadd($x, $xs, $y, $ys);
}
sub _e_sub {
my ($x, $y, $xs, $ys) = @_;
return $LIB -> _ssub($x, $xs, $y, $ys);
}
1;
__END__
=pod
=head1 NAME
Math::BigFloat - arbitrary size floating point math package
=head1 SYNOPSIS
use Math::BigFloat;
# Configuration methods (may be used as class methods and instance methods)
Math::BigFloat->accuracy($n); # set accuracy
Math::BigFloat->accuracy(); # get accuracy
Math::BigFloat->precision($n); # set precision
Math::BigFloat->precision(); # get precision
Math::BigFloat->round_mode($m); # set rounding mode, must be
# 'even', 'odd', '+inf', '-inf',
# 'zero', 'trunc', or 'common'
Math::BigFloat->round_mode(); # get class rounding mode
Math::BigFloat->div_scale($n); # set fallback accuracy
Math::BigFloat->div_scale(); # get fallback accuracy
Math::BigFloat->trap_inf($b); # trap infinities or not
Math::BigFloat->trap_inf(); # get trap infinities status
Math::BigFloat->trap_nan($b); # trap NaNs or not
Math::BigFloat->trap_nan(); # get trap NaNs status
Math::BigFloat->config($par, $val); # set configuration parameter
Math::BigFloat->config($par); # get configuration parameter
Math::BigFloat->config(); # get hash with configuration
Math::BigFloat->config("lib"); # get name of backend library
# Generic constructor method (always returns a new object)
$x = Math::BigFloat->new($str); # defaults to 0
$x = Math::BigFloat->new('256'); # from decimal
$x = Math::BigFloat->new('0256'); # from decimal
$x = Math::BigFloat->new('0xcafe'); # from hexadecimal
$x = Math::BigFloat->new('0x1.cafep+7'); # from hexadecimal
$x = Math::BigFloat->new('0o377'); # from octal
$x = Math::BigFloat->new('0o1.3571p+6'); # from octal
$x = Math::BigFloat->new('0b101'); # from binary
$x = Math::BigFloat->new('0b1.101p+3'); # from binary
# Specific constructor methods (no prefix needed; when used as
# instance method, the value is assigned to the invocand)
$x = Math::BigFloat->from_dec('234'); # from decimal
$x = Math::BigFloat->from_hex('c.afep+3'); # from hexadecimal
$x = Math::BigFloat->from_hex('cafe'); # from hexadecimal
$x = Math::BigFloat->from_oct('1.3267p-4'); # from octal
$x = Math::BigFloat->from_oct('377'); # from octal
$x = Math::BigFloat->from_bin('0b1.1001p-4'); # from binary
$x = Math::BigFloat->from_bin('0101'); # from binary
$x = Math::BigFloat->from_bytes($bytes); # from byte string
$x = Math::BigFloat->from_base('why', 36); # from any base
$x = Math::BigFloat->from_ieee754($b, $fmt); # from IEEE-754 bytes
$x = Math::BigFloat->bzero(); # create a +0
$x = Math::BigFloat->bone(); # create a +1
$x = Math::BigFloat->bone('-'); # create a -1
$x = Math::BigFloat->binf(); # create a +inf
$x = Math::BigFloat->binf('-'); # create a -inf
$x = Math::BigFloat->bnan(); # create a Not-A-Number
$x = Math::BigFloat->bpi(); # returns pi
$y = $x->copy(); # make a copy (unlike $y = $x)
$y = $x->as_int(); # return as BigInt
$y = $x->as_float(); # return as a Math::BigFloat
$y = $x->as_rat(); # return as a Math::BigRat
# Boolean methods (these don't modify the invocand)
$x->is_zero(); # true if $x is 0
$x->is_one(); # true if $x is +1
$x->is_one("+"); # true if $x is +1
$x->is_one("-"); # true if $x is -1
$x->is_inf(); # true if $x is +inf or -inf
$x->is_inf("+"); # true if $x is +inf
$x->is_inf("-"); # true if $x is -inf
$x->is_nan(); # true if $x is NaN
$x->is_finite(); # true if -inf < $x < inf
$x->is_positive(); # true if $x > 0
$x->is_pos(); # true if $x > 0
$x->is_negative(); # true if $x < 0
$x->is_neg(); # true if $x < 0
$x->is_non_positive() # true if $x <= 0
$x->is_non_negative() # true if $x >= 0
$x->is_odd(); # true if $x is odd
$x->is_even(); # true if $x is even
$x->is_int(); # true if $x is an integer
# Comparison methods (these don't modify the invocand)
$x->bcmp($y); # compare numbers (undef, < 0, == 0, > 0)
$x->bacmp($y); # compare abs values (undef, < 0, == 0, > 0)
$x->beq($y); # true if $x == $y
$x->bne($y); # true if $x != $y
$x->blt($y); # true if $x < $y
$x->ble($y); # true if $x <= $y
$x->bgt($y); # true if $x > $y
$x->bge($y); # true if $x >= $y
# Arithmetic methods (these modify the invocand)
$x->bneg(); # negation
$x->babs(); # absolute value
$x->bsgn(); # sign function (-1, 0, 1, or NaN)
$x->binc(); # increment $x by 1
$x->bdec(); # decrement $x by 1
$x->badd($y); # addition (add $y to $x)
$x->bsub($y); # subtraction (subtract $y from $x)
$x->bmul($y); # multiplication (multiply $x by $y)
$x->bmuladd($y, $z); # $x = $x * $y + $z
$x->bdiv($y); # division (floored), set $x to quotient
$x->bmod($y); # modulus (x % y)
$x->bmodinv($mod); # modular multiplicative inverse
$x->bmodpow($y, $mod); # modular exponentiation (($x ** $y) % $mod)
$x->btdiv($y); # division (truncated), set $x to quotient
$x->btmod($y); # modulus (truncated)
$x->binv() # inverse (1/$x)
$x->bpow($y); # power of arguments (x ** y)
$x->blog(); # logarithm of $x to base e (Euler's number)
$x->blog($base); # logarithm of $x to base $base (e.g., base 2)
$x->bexp(); # calculate e ** $x where e is Euler's number
$x->bilog2(); # log2($x) rounded down to nearest int
$x->bilog10(); # log10($x) rounded down to nearest int
$x->bclog2(); # log2($x) rounded up to nearest int
$x->bclog10(); # log10($x) rounded up to nearest int
$x->bnok($y); # combinations (binomial coefficient n over k)
$x->bperm($y); # permutations
$x->bsin(); # sine
$x->bcos(); # cosine
$x->batan(); # inverse tangent
$x->batan2($y); # two-argument inverse tangent
$x->bsqrt(); # calculate square root
$x->broot($y); # $y'th root of $x (e.g. $y == 3 => cubic root)
$x->bfac(); # factorial of $x (1*2*3*4*..$x)
$x->bdfac(); # double factorial of $x ($x*($x-2)*($x-4)*...)
$x->btfac(); # triple factorial of $x ($x*($x-3)*($x-6)*...)
$x->bmfac($k); # $k'th multi-factorial of $x ($x*($x-$k)*...)
$x->bfib($k); # $k'th Fibonacci number
$x->blucas($k); # $k'th Lucas number
$x->blsft($n); # left shift $n places in base 2
$x->blsft($n, $b); # left shift $n places in base $b
$x->brsft($n); # right shift $n places in base 2
$x->brsft($n, $b); # right shift $n places in base $b
# Bitwise methods (these modify the invocand)
$x->bblsft($y); # bitwise left shift
$x->bbrsft($y); # bitwise right shift
$x->band($y); # bitwise and
$x->bior($y); # bitwise inclusive or
$x->bxor($y); # bitwise exclusive or
$x->bnot(); # bitwise not (two's complement)
# Rounding methods (these modify the invocand)
$x->round($A, $P, $R); # round to accuracy or precision using
# rounding mode $R
$x->bround($n); # accuracy: preserve $n digits
$x->bfround($n); # $n > 0: round to $nth digit left of dec. point
# $n < 0: round to $nth digit right of dec. point
$x->bfloor(); # round towards minus infinity
$x->bceil(); # round towards plus infinity
$x->bint(); # round towards zero
# Other mathematical methods (these don't modify the invocand)
$x->bgcd($y); # greatest common divisor
$x->blcm($y); # least common multiple
# Object property methods (these don't modify the invocand)
$x->sign(); # the sign, either +, - or NaN
$x->digit($n); # the nth digit, counting from the right
$x->digit(-$n); # the nth digit, counting from the left
$x->length(); # return number of digits in number
$x->mantissa(); # return (signed) mantissa as BigInt
$x->exponent(); # return exponent as BigInt
$x->parts(); # return (mantissa,exponent) as BigInt
$x->sparts(); # mantissa and exponent (as integers)
$x->nparts(); # mantissa and exponent (normalised)
$x->eparts(); # mantissa and exponent (engineering notation)
$x->dparts(); # integer and fraction part
$x->fparts(); # numerator and denominator
$x->numerator(); # numerator
$x->denominator(); # denominator
# Conversion methods (these don't modify the invocand)
$x->bstr(); # decimal notation (possibly zero padded)
$x->bsstr(); # string in scientific notation with integers
$x->bnstr(); # string in normalized notation
$x->bestr(); # string in engineering notation
$x->bdstr(); # string in decimal notation (no padding)
$x->bfstr(); # string in fractional notation
$x->to_hex(); # as signed hexadecimal string
$x->to_bin(); # as signed binary string
$x->to_oct(); # as signed octal string
$x->to_bytes(); # as byte string
$x->to_ieee754($fmt); # to bytes encoded according to IEEE 754-2008
$x->as_hex(); # as signed hexadecimal string with "0x" prefix
$x->as_bin(); # as signed binary string with "0b" prefix
$x->as_oct(); # as signed octal string with "0" prefix
# Other conversion methods (these don't modify the invocand)
$x->numify(); # return as scalar (might overflow or underflow)
=head1 DESCRIPTION
Math::BigFloat provides support for arbitrary precision floating point.
Overloading is also provided for Perl operators.
All operators (including basic math operations) are overloaded if you
declare your big floating point numbers as
$x = Math::BigFloat -> new('12_3.456_789_123_456_789E-2');
Operations with overloaded operators preserve the arguments, which is
exactly what you expect.
=head2 Input
Input values to these routines may be any scalar number or string that looks
like a number. Anything that is accepted by Perl as a literal numeric constant
should be accepted by this module.
=over
=item *
Leading and trailing whitespace is ignored.
=item *
Leading zeros are ignored, except for floating point numbers with a binary
exponent, in which case the number is interpreted as an octal floating point
number. For example, "01.4p+0" gives 1.5, "00.4p+0" gives 0.5, but "0.4p+0"
gives a NaN. And while "0377" gives 255, "0377p0" gives 255.
=item *
If the string has a "0x" or "0X" prefix, it is interpreted as a hexadecimal
number.
=item *
If the string has a "0o" or "0O" prefix, it is interpreted as an octal number.
A floating point literal with a "0" prefix is also interpreted as an octal
number.
=item *
If the string has a "0b" or "0B" prefix, it is interpreted as a binary number.
=item *
Underline characters are allowed in the same way as they are allowed in literal
numerical constants.
=item *
If the string can not be interpreted, NaN is returned.
=item *
For hexadecimal, octal, and binary floating point numbers, the exponent must be
separated from the significand (mantissa) by the letter "p" or "P", not "e" or
"E" as with decimal numbers.
=back
Some examples of valid string input
Input string Resulting value
123 123
1.23e2 123
12300e-2 123
67_538_754 67538754
-4_5_6.7_8_9e+0_1_0 -4567890000000
0x13a 314
0x13ap0 314
0x1.3ap+8 314
0x0.00013ap+24 314
0x13a000p-12 314
0o472 314
0o1.164p+8 314
0o0.0001164p+20 314
0o1164000p-10 314
0472 472 Note!
01.164p+8 314
00.0001164p+20 314
01164000p-10 314
0b100111010 314
0b1.0011101p+8 314
0b0.00010011101p+12 314
0b100111010000p-3 314
0x1.921fb5p+1 3.14159262180328369140625e+0
0o1.2677025p1 2.71828174591064453125
01.2677025p1 2.71828174591064453125
0b1.1001p-4 9.765625e-2
=head2 Output
Output values are usually Math::BigFloat objects.
Boolean operators L<is_zero()|Math::BigInt/is_zero()>,
L<is_one()|Math::BigInt/is_one()>, L<is_inf()|Math::BigInt/is_inf()>, etc.
return true or false.
Comparison operators L<bcmp()|Math::BigInt/bcmp()> and
L<bacmp()|Math::BigInt/bacmp()>) return -1, 0, 1, or undef.
=head1 METHODS
Math::BigFloat supports all methods that Math::BigInt supports, except it
calculates non-integer results when possible. Please see L<Math::BigInt> for a
full description of each method. Below are just the most important differences:
=head2 Configuration methods
=over
=item accuracy()
$x->accuracy(5); # local for $x
CLASS->accuracy(5); # global for all members of CLASS
# Note: This also applies to new()!
$A = $x->accuracy(); # read out accuracy that affects $x
$A = CLASS->accuracy(); # read out global accuracy
Set or get the global or local accuracy, aka how many significant digits the
results have. If you set a global accuracy, then this also applies to new()!
Warning! The accuracy I<sticks>, e.g. once you created a number under the
influence of C<< CLASS->accuracy($A) >>, all results from math operations with
that number will also be rounded.
In most cases, you should probably round the results explicitly using one of
L<Math::BigInt/round()>, L<Math::BigInt/bround()> or L<Math::BigInt/bfround()>
or by passing the desired accuracy to the math operation as additional
parameter:
my $x = Math::BigInt->new(30000);
my $y = Math::BigInt->new(7);
print scalar $x->copy()->bdiv($y, 2); # print 4300
print scalar $x->copy()->bdiv($y)->bround(2); # print 4300
=item precision()
$x->precision(-2); # local for $x, round at the second
# digit right of the dot
$x->precision(2); # ditto, round at the second digit
# left of the dot
CLASS->precision(5); # Global for all members of CLASS
# This also applies to new()!
CLASS->precision(-5); # ditto
$P = CLASS->precision(); # read out global precision
$P = $x->precision(); # read out precision that affects $x
Note: You probably want to use L</accuracy()> instead. With L</accuracy()> you
set the number of digits each result should have, with L</precision()> you
set the place where to round!
=back
=head2 Constructor methods
=over
=item from_dec()
$x -> from_hex("314159");
$x = Math::BigInt -> from_hex("314159");
Interpret input as a decimal. It is equivalent to new(), but does not accept
anything but strings representing finite, decimal numbers.
=item from_hex()
$x -> from_hex("0x1.921fb54442d18p+1");
$x = Math::BigFloat -> from_hex("0x1.921fb54442d18p+1");
Interpret input as a hexadecimal string.A prefix ("0x", "x", ignoring case) is
optional. A single underscore character ("_") may be placed between any two
digits. If the input is invalid, a NaN is returned. The exponent is in base 2
using decimal digits.
If called as an instance method, the value is assigned to the invocand.
=item from_oct()
$x -> from_oct("1.3267p-4");
$x = Math::BigFloat -> from_oct("1.3267p-4");
Interpret input as an octal string. A single underscore character ("_") may be
placed between any two digits. If the input is invalid, a NaN is returned. The
exponent is in base 2 using decimal digits.
If called as an instance method, the value is assigned to the invocand.
=item from_bin()
$x -> from_bin("0b1.1001p-4");
$x = Math::BigFloat -> from_bin("0b1.1001p-4");
Interpret input as a hexadecimal string. A prefix ("0b" or "b", ignoring case)
is optional. A single underscore character ("_") may be placed between any two
digits. If the input is invalid, a NaN is returned. The exponent is in base 2
using decimal digits.
If called as an instance method, the value is assigned to the invocand.
=item from_bytes()
$x = Math::BigFloat->from_bytes("\xf3\x6b"); # $x = 62315
Interpret the input as a byte string, assuming big endian byte order. The
output is always a non-negative, finite integer.
See L<Math::BigInt/from_bytes()>.
=item from_ieee754()
Interpret the input as a value encoded as described in IEEE754-2008. The input
can be given as a byte string, hex string, or binary string. The input is
assumed to be in big-endian byte-order.
# Both $dbl, $xr, $xh, and $xb below are 3.141592...
$dbl = unpack "d>", "\x40\x09\x21\xfb\x54\x44\x2d\x18";
$raw = "\x40\x09\x21\xfb\x54\x44\x2d\x18"; # raw bytes
$xr = Math::BigFloat -> from_ieee754($raw, "binary64");
$hex = "400921fb54442d18";
$xh = Math::BigFloat -> from_ieee754($hex, "binary64");
$bin = "0100000000001001001000011111101101010100010001000010110100011000";
$xb = Math::BigFloat -> from_ieee754($bin, "binary64");
Supported formats are all IEEE 754 binary formats: "binary16", "binary32",
"binary64", "binary128", "binary160", "binary192", "binary224", "binary256",
etc. where the number of bits is a multiple of 32 for all formats larger than
"binary128". Aliases are "half" ("binary16"), "single" ("binary32"), "double"
("binary64"), "quadruple" ("binary128"), "octuple" ("binary256"), and
"sexdecuple" ("binary512").
See also L</to_ieee754()>.
=item from_base()
See L<Math::BigInt/from_base()>.
=item bpi()
print Math::BigFloat->bpi(100), "\n";
Calculate PI to N digits (including the 3 before the dot). The result is
rounded according to the current rounding mode, which defaults to "even".
This method was added in v1.87 of Math::BigInt (June 2007).
=item as_int()
$y = $x -> as_int(); # $y is a Math::BigInt
Returns $x as a Math::BigInt object regardless of upgrading and downgrading. If
$x is finite, but not an integer, $x is truncated.
=item as_rat()
$y = $x -> as_rat(); # $y is a Math::BigRat
Returns $x a Math::BigRat object regardless of upgrading and downgrading. The
invocand is not modified.
=item as_float()
$y = $x -> as_float(); # $y is a Math::BigFloat
Returns $x a Math::BigFloat object regardless of upgrading and downgrading. The
invocand is not modified.
=back
=head2 Arithmetic methods
=over
=item bdiv()
$x->bdiv($y); # set $x to quotient
($q, $r) = $x->bdiv($y); # also remainder
This is an alias for L</bfdiv()>.
=item bmod()
$x->bmod($y);
Returns $x modulo $y. When $x is finite, and $y is finite and non-zero, the
result is identical to the remainder after floored division (F-division). If,
in addition, both $x and $y are integers, the result is identical to the result
from Perl's % operator.
=item bfdiv()
$q = $x->bfdiv($y);
($q, $r) = $x->bfdiv($y);
In scalar context, divides $x by $y and returns the result to the given
accuracy or precision or the default accuracy. In list context, does floored
division (F-division), returning an integer $q and a remainder $r
$q = floor($x / $y)
$r = $x - $q * $y
so that the following relationship always holds
$x = $q * $y + $r
The remainer (modulo) is equal to what is returned by C<< $x->bmod($y) >>.
=item binv()
$x->binv();
Invert the value of $x, i.e., compute 1/$x.
=item bmuladd()
$x->bmuladd($y,$z);
Multiply $x by $y, and then add $z to the result.
This method was added in v1.87 of Math::BigInt (June 2007).
=item bexp()
$x->bexp($accuracy); # calculate e ** X
Calculates the expression C<e ** $x> where C<e> is Euler's number.
This method was added in v1.82 of Math::BigInt (April 2007).
=item bnok()
See L<Math::BigInt/bnok()>.
=item bperm()
See L<Math::BigInt/bperm()>.
=item bsin()
my $x = Math::BigFloat->new(1);
print $x->bsin(100), "\n";
Calculate the sinus of $x, modifying $x in place.
This method was added in v1.87 of Math::BigInt (June 2007).
=item bcos()
my $x = Math::BigFloat->new(1);
print $x->bcos(100), "\n";
Calculate the cosinus of $x, modifying $x in place.
This method was added in v1.87 of Math::BigInt (June 2007).
=item batan()
my $x = Math::BigFloat->new(1);
print $x->batan(100), "\n";
Calculate the arcus tanges of $x, modifying $x in place. See also L</batan2()>.
This method was added in v1.87 of Math::BigInt (June 2007).
=item batan2()
my $y = Math::BigFloat->new(2);
my $x = Math::BigFloat->new(3);
print $y->batan2($x), "\n";
Calculate the arcus tanges of C<$y> divided by C<$x>, modifying $y in place.
See also L</batan()>.
This method was added in v1.87 of Math::BigInt (June 2007).
=item bgcd()
$x -> bgcd($y); # GCD of $x and $y
$x -> bgcd($y, $z, ...); # GCD of $x, $y, $z, ...
Returns the greatest common divisor (GCD), which is the number with the largest
absolute value such that $x/$gcd, $y/$gcd, ... is an integer. For example, when
the operands are 0.8 and 1.2, the GCD is 0.4. This is a generalisation of the
ordinary GCD for integers. See L<Math::BigInt/gcd()>.
=back
=head2 String conversion methods
=over
=item bstr()
my $x = Math::BigRat->new('8/4');
print $x->bstr(), "\n"; # prints 1/2
Returns a string representing the number.
=item bsstr()
See L<Math::BigInt/bsstr()>.
=item bnstr()
See L<Math::BigInt/bnstr()>.
=item bestr()
See L<Math::BigInt/bestr()>.
=item bdstr()
See L<Math::BigInt/bdstr()>.
=item to_bytes()
See L<Math::BigInt/to_bytes()>.
=item to_ieee754()
Encodes the invocand as a byte string in the given format as specified in IEEE
754-2008. Note that the encoded value is the nearest possible representation of
the value. This value might not be exactly the same as the value in the
invocand.
# $x = 3.1415926535897932385
$x = Math::BigFloat -> bpi(30);
$b = $x -> to_ieee754("binary64"); # encode as 8 bytes
$h = unpack "H*", $b; # "400921fb54442d18"
# 3.141592653589793115997963...
$y = Math::BigFloat -> from_ieee754($h, "binary64");
All binary formats in IEEE 754-2008 are accepted. For convenience, som aliases
are recognized: "half" for "binary16", "single" for "binary32", "double" for
"binary64", "quadruple" for "binary128", "octuple" for "binary256", and
"sexdecuple" for "binary512".
See also L</from_ieee754()>, L<https://en.wikipedia.org/wiki/IEEE_754>.
=back
=head2 ACCURACY AND PRECISION
See also: L<Rounding|/Rounding>.
Math::BigFloat supports both precision (rounding to a certain place before or
after the dot) and accuracy (rounding to a certain number of digits). For a
full documentation, examples and tips on these topics please see the large
section about rounding in L<Math::BigInt>.
Since things like C<sqrt(2)> or C<1 / 3> must presented with a limited
accuracy lest a operation consumes all resources, each operation produces
no more than the requested number of digits.
If there is no global precision or accuracy set, B<and> the operation in
question was not called with a requested precision or accuracy, B<and> the
input $x has no accuracy or precision set, then a fallback parameter will
be used. For historical reasons, it is called C<div_scale> and can be accessed
via:
$d = Math::BigFloat->div_scale(); # query
Math::BigFloat->div_scale($n); # set to $n digits
The default value for C<div_scale> is 40.
In case the result of one operation has more digits than specified,
it is rounded. The rounding mode taken is either the default mode, or the one
supplied to the operation after the I<scale>:
$x = Math::BigFloat->new(2);
Math::BigFloat->accuracy(5); # 5 digits max
$y = $x->copy()->bdiv(3); # gives 0.66667
$y = $x->copy()->bdiv(3,6); # gives 0.666667
$y = $x->copy()->bdiv(3,6,undef,'odd'); # gives 0.666667
Math::BigFloat->round_mode('zero');
$y = $x->copy()->bdiv(3,6); # will also give 0.666667
Note that C<< Math::BigFloat->accuracy() >> and
C<< Math::BigFloat->precision() >> set the global variables, and thus B<any>
newly created number will be subject to the global rounding B<immediately>.
This means that in the examples above, the C<3> as argument to L</bdiv()> will
also get an accuracy of B<5>.
It is less confusing to either calculate the result fully, and afterwards
round it explicitly, or use the additional parameters to the math
functions like so:
use Math::BigFloat;
$x = Math::BigFloat->new(2);
$y = $x->copy()->bdiv(3);
print $y->bround(5),"\n"; # gives 0.66667
or
use Math::BigFloat;
$x = Math::BigFloat->new(2);
$y = $x->copy()->bdiv(3,5); # gives 0.66667
print "$y\n";
=head2 Rounding
=over
=item bfround ( +$scale )
Rounds to the $scale'th place left from the '.', counting from the dot.
The first digit is numbered 1.
=item bfround ( -$scale )
Rounds to the $scale'th place right from the '.', counting from the dot.
=item bfround ( 0 )
Rounds to an integer.
=item bround ( +$scale )
Preserves accuracy to $scale digits from the left (aka significant digits) and
pads the rest with zeros. If the number is between 1 and -1, the significant
digits count from the first non-zero after the '.'
=item bround ( -$scale ) and bround ( 0 )
These are effectively no-ops.
=back
All rounding functions take as a second parameter a rounding mode from one of
the following: 'even', 'odd', '+inf', '-inf', 'zero', 'trunc' or 'common'.
The default rounding mode is 'even'. By using
C<< Math::BigFloat->round_mode($round_mode); >> you can get and set the default
mode for subsequent rounding. The usage of C<$Math::BigFloat::$round_mode> is
no longer supported.
The second parameter to the round functions then overrides the default
temporarily.
The L</as_int()> method returns a BigInt from a Math::BigFloat. It uses 'trunc'
as rounding mode to make it equivalent to:
$x = 2.5;
$y = int($x) + 2;
You can override this by passing the desired rounding mode as parameter to
L</as_int()>:
$x = Math::BigFloat->new(2.5);
$y = $x->as_number('odd'); # $y = 3
=head1 NUMERIC LITERALS
After C<use Math::BigFloat ':constant'> all numeric literals in the given scope
are converted to C<Math::BigFloat> objects. This conversion happens at compile
time.
For example,
perl -MMath::BigFloat=:constant -le 'print 2e-150'
prints the exact value of C<2e-150>. Note that without conversion of constants
the expression C<2e-150> is calculated using Perl scalars, which leads to an
inaccuracte result.
Note that strings are not affected, so that
use Math::BigFloat qw/:constant/;
$y = "1234567890123456789012345678901234567890"
+ "123456789123456789";
does not give you what you expect. You need an explicit Math::BigFloat->new()
around at least one of the operands. You should also quote large constants to
prevent loss of precision:
use Math::BigFloat;
$x = Math::BigFloat->new("1234567889123456789123456789123456789");
Without the quotes Perl converts the large number to a floating point constant
at compile time, and then converts the result to a Math::BigFloat object at
runtime, which results in an inaccurate result.
=head2 Hexadecimal, octal, and binary floating point literals
Perl (and this module) accepts hexadecimal, octal, and binary floating point
literals, but use them with care with Perl versions before v5.32.0, because
some versions of Perl silently give the wrong result. Below are some examples
of different ways to write the number decimal 314.
Hexadecimal floating point literals:
0x1.3ap+8 0X1.3AP+8
0x1.3ap8 0X1.3AP8
0x13a0p-4 0X13A0P-4
Octal floating point literals (with "0" prefix):
01.164p+8 01.164P+8
01.164p8 01.164P8
011640p-4 011640P-4
Octal floating point literals (with "0o" prefix) (requires v5.34.0):
0o1.164p+8 0O1.164P+8
0o1.164p8 0O1.164P8
0o11640p-4 0O11640P-4
Binary floating point literals:
0b1.0011101p+8 0B1.0011101P+8
0b1.0011101p8 0B1.0011101P8
0b10011101000p-2 0B10011101000P-2
=head2 Math library
Math with the numbers is done (by default) by a module called
Math::BigInt::Calc. This is equivalent to saying:
use Math::BigFloat lib => "Calc";
You can change this by using:
use Math::BigFloat lib => "GMP";
B<Note>: General purpose packages should not be explicit about the library to
use; let the script author decide which is best.
Note: The keyword 'lib' will warn when the requested library could not be
loaded. To suppress the warning use 'try' instead:
use Math::BigFloat try => "GMP";
If your script works with huge numbers and Calc is too slow for them, you can
also for the loading of one of these libraries and if none of them can be used,
the code will die:
use Math::BigFloat only => "GMP,Pari";
The following would first try to find Math::BigInt::Foo, then
Math::BigInt::Bar, and when this also fails, revert to Math::BigInt::Calc:
use Math::BigFloat lib => "Foo,Math::BigInt::Bar";
See the respective low-level library documentation for further details.
See L<Math::BigInt> for more details about using a different low-level library.
=head1 EXPORTS
C<Math::BigFloat> exports nothing by default, but can export the L</bpi()>
method:
use Math::BigFloat qw/bpi/;
print bpi(10), "\n";
=over
=item Modifying and =
Beware of:
$x = Math::BigFloat->new(5);
$y = $x;
It will not do what you think, e.g. making a copy of $x. Instead it just makes
a second reference to the B<same> object and stores it in $y. Thus anything
that modifies $x will modify $y (except overloaded math operators), and vice
versa. See L<Math::BigInt> for details and how to avoid that.
=item precision() vs. accuracy()
A common pitfall is to use L</precision()> when you want to round a result to
a certain number of digits:
use Math::BigFloat;
Math::BigFloat->precision(4); # does not do what you
# think it does
my $x = Math::BigFloat->new(12345); # rounds $x to "12000"!
print "$x\n"; # print "12000"
my $y = Math::BigFloat->new(3); # rounds $y to "0"!
print "$y\n"; # print "0"
$z = $x / $y; # 12000 / 0 => NaN!
print "$z\n";
print $z->precision(),"\n"; # 4
Replacing L</precision()> with L</accuracy()> is probably not what you want,
either:
use Math::BigFloat;
Math::BigFloat->accuracy(4); # enables global rounding:
my $x = Math::BigFloat->new(123456); # rounded immediately
# to "12350"
print "$x\n"; # print "123500"
my $y = Math::BigFloat->new(3); # rounded to "3
print "$y\n"; # print "3"
print $z = $x->copy()->bdiv($y),"\n"; # 41170
print $z->accuracy(),"\n"; # 4
What you want to use instead is:
use Math::BigFloat;
my $x = Math::BigFloat->new(123456); # no rounding
print "$x\n"; # print "123456"
my $y = Math::BigFloat->new(3); # no rounding
print "$y\n"; # print "3"
print $z = $x->copy()->bdiv($y,4),"\n"; # 41150
print $z->accuracy(),"\n"; # undef
In addition to computing what you expected, the last example also does B<not>
"taint" the result with an accuracy or precision setting, which would
influence any further operation.
=back
=head1 BUGS
Please report any bugs or feature requests to
C<bug-math-bigint at rt.cpan.org>, or through the web interface at
L<https://rt.cpan.org/Ticket/Create.html?Queue=Math-BigInt> (requires login).
We will be notified, and then you'll automatically be notified of progress on
your bug as I make changes.
=head1 SUPPORT
You can find documentation for this module with the perldoc command.
perldoc Math::BigFloat
You can also look for information at:
=over 4
=item * GitHub
L<https://github.com/pjacklam/p5-Math-BigInt>
=item * RT: CPAN's request tracker
L<https://rt.cpan.org/Dist/Display.html?Name=Math-BigInt>
=item * MetaCPAN
L<https://metacpan.org/release/Math-BigInt>
=item * CPAN Testers Matrix
L<http://matrix.cpantesters.org/?dist=Math-BigInt>
=back
=head1 LICENSE
This program is free software; you may redistribute it and/or modify it under
the same terms as Perl itself.
=head1 SEE ALSO
L<Math::BigInt> and L<Math::BigRat> as well as the backend libraries
L<Math::BigInt::FastCalc>, L<Math::BigInt::GMP>, and L<Math::BigInt::Pari>,
L<Math::BigInt::GMPz>, and L<Math::BigInt::BitVect>.
The pragmas L<bigint>, L<bigfloat>, and L<bigrat> might also be of interest. In
addition there is the L<bignum> pragma which does upgrading and downgrading.
=head1 AUTHORS
=over 4
=item *
Mark Biggar, overloaded interface by Ilya Zakharevich, 1996-2001.
=item *
Completely rewritten by Tels L<http://bloodgate.com> in 2001-2008.
=item *
Florian Ragwitz E<lt>flora@cpan.orgE<gt>, 2010.
=item *
Peter John Acklam E<lt>pjacklam@gmail.comE<gt>, 2011-.
=back
=cut
|