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
|
/*
*
* Ruby BigDecimal(Variable decimal precision) extension library.
*
* Copyright(C) 2002 by Shigeo Kobayashi(shigeo@tinyforest.gr.jp)
*
*/
/* #define BIGDECIMAL_DEBUG 1 */
#ifdef BIGDECIMAL_DEBUG
# define BIGDECIMAL_ENABLE_VPRINT 1
#endif
#include "bigdecimal.h"
#include "ruby/util.h"
#ifndef BIGDECIMAL_DEBUG
# undef NDEBUG
# define NDEBUG
#endif
#include <assert.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <math.h>
#ifdef HAVE_IEEEFP_H
#include <ieeefp.h>
#endif
#include "bits.h"
#include "static_assert.h"
/* #define ENABLE_NUMERIC_STRING */
#define SIGNED_VALUE_MAX INTPTR_MAX
#define SIGNED_VALUE_MIN INTPTR_MIN
#define MUL_OVERFLOW_SIGNED_VALUE_P(a, b) MUL_OVERFLOW_SIGNED_INTEGER_P(a, b, SIGNED_VALUE_MIN, SIGNED_VALUE_MAX)
VALUE rb_cBigDecimal;
VALUE rb_mBigMath;
static ID id_BigDecimal_exception_mode;
static ID id_BigDecimal_rounding_mode;
static ID id_BigDecimal_precision_limit;
static ID id_up;
static ID id_down;
static ID id_truncate;
static ID id_half_up;
static ID id_default;
static ID id_half_down;
static ID id_half_even;
static ID id_banker;
static ID id_ceiling;
static ID id_ceil;
static ID id_floor;
static ID id_to_r;
static ID id_eq;
static ID id_half;
/* MACRO's to guard objects from GC by keeping them in stack */
#ifdef RBIMPL_ATTR_MAYBE_UNUSED
#define ENTER(n) RBIMPL_ATTR_MAYBE_UNUSED() volatile VALUE vStack[n];int iStack=0
#else
#define ENTER(n) volatile VALUE RB_UNUSED_VAR(vStack[n]);int iStack=0
#endif
#define PUSH(x) (vStack[iStack++] = (VALUE)(x))
#define SAVE(p) PUSH((p)->obj)
#define GUARD_OBJ(p,y) ((p)=(y), SAVE(p))
#define BASE_FIG BIGDECIMAL_COMPONENT_FIGURES
#define BASE BIGDECIMAL_BASE
#define HALF_BASE (BASE/2)
#define BASE1 (BASE/10)
#define LOG10_2 0.3010299956639812
#ifndef RRATIONAL_ZERO_P
# define RRATIONAL_ZERO_P(x) (FIXNUM_P(rb_rational_num(x)) && \
FIX2LONG(rb_rational_num(x)) == 0)
#endif
#ifndef RRATIONAL_NEGATIVE_P
# define RRATIONAL_NEGATIVE_P(x) RTEST(rb_funcall((x), '<', 1, INT2FIX(0)))
#endif
#ifndef DECIMAL_SIZE_OF_BITS
#define DECIMAL_SIZE_OF_BITS(n) (((n) * 3010 + 9998) / 9999)
/* an approximation of ceil(n * log10(2)), upto 65536 at least */
#endif
#ifdef PRIsVALUE
# define RB_OBJ_CLASSNAME(obj) rb_obj_class(obj)
# define RB_OBJ_STRING(obj) (obj)
#else
# define PRIsVALUE "s"
# define RB_OBJ_CLASSNAME(obj) rb_obj_classname(obj)
# define RB_OBJ_STRING(obj) StringValueCStr(obj)
#endif
#define BIGDECIMAL_POSITIVE_P(bd) ((bd)->sign > 0)
#define BIGDECIMAL_NEGATIVE_P(bd) ((bd)->sign < 0)
/*
* ================== Ruby Interface part ==========================
*/
#define DoSomeOne(x,y,f) rb_num_coerce_bin(x,y,f)
/*
* VP routines used in BigDecimal part
*/
static unsigned short VpGetException(void);
static void VpSetException(unsigned short f);
static void VpCheckException(Real *p, bool always);
static VALUE VpCheckGetValue(Real *p);
static void VpInternalRound(Real *c, size_t ixDigit, DECDIG vPrev, DECDIG v);
static int VpLimitRound(Real *c, size_t ixDigit);
static Real *VpCopy(Real *pv, Real const* const x);
#ifdef BIGDECIMAL_ENABLE_VPRINT
static int VPrint(FILE *fp,const char *cntl_chr,Real *a);
#endif
/*
* **** BigDecimal part ****
*/
static VALUE BigDecimal_nan(void);
static VALUE BigDecimal_positive_infinity(void);
static VALUE BigDecimal_negative_infinity(void);
static VALUE BigDecimal_positive_zero(void);
static VALUE BigDecimal_negative_zero(void);
static void
BigDecimal_delete(void *pv)
{
VpFree(pv);
}
static size_t
BigDecimal_memsize(const void *ptr)
{
const Real *pv = ptr;
return (sizeof(*pv) + pv->MaxPrec * sizeof(DECDIG));
}
#ifndef HAVE_RB_EXT_RACTOR_SAFE
# undef RUBY_TYPED_FROZEN_SHAREABLE
# define RUBY_TYPED_FROZEN_SHAREABLE 0
#endif
static const rb_data_type_t BigDecimal_data_type = {
"BigDecimal",
{ 0, BigDecimal_delete, BigDecimal_memsize, },
#ifdef RUBY_TYPED_FREE_IMMEDIATELY
0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_FROZEN_SHAREABLE
#endif
};
static inline int
is_kind_of_BigDecimal(VALUE const v)
{
return rb_typeddata_is_kind_of(v, &BigDecimal_data_type);
}
NORETURN(static void cannot_be_coerced_into_BigDecimal(VALUE, VALUE));
static void
cannot_be_coerced_into_BigDecimal(VALUE exc_class, VALUE v)
{
VALUE str;
if (rb_special_const_p(v)) {
str = rb_inspect(v);
}
else {
str = rb_class_name(rb_obj_class(v));
}
str = rb_str_cat2(rb_str_dup(str), " can't be coerced into BigDecimal");
rb_exc_raise(rb_exc_new3(exc_class, str));
}
static inline VALUE BigDecimal_div2(VALUE, VALUE, VALUE);
static VALUE rb_inum_convert_to_BigDecimal(VALUE val, size_t digs, int raise_exception);
static VALUE rb_float_convert_to_BigDecimal(VALUE val, size_t digs, int raise_exception);
static VALUE rb_rational_convert_to_BigDecimal(VALUE val, size_t digs, int raise_exception);
static VALUE rb_cstr_convert_to_BigDecimal(const char *c_str, size_t digs, int raise_exception);
static VALUE rb_convert_to_BigDecimal(VALUE val, size_t digs, int raise_exception);
static Real*
GetVpValueWithPrec(VALUE v, long prec, int must)
{
const size_t digs = prec < 0 ? SIZE_MAX : (size_t)prec;
switch(TYPE(v)) {
case T_FLOAT:
v = rb_float_convert_to_BigDecimal(v, digs, must);
break;
case T_RATIONAL:
v = rb_rational_convert_to_BigDecimal(v, digs, must);
break;
case T_DATA:
if (!is_kind_of_BigDecimal(v)) {
goto SomeOneMayDoIt;
}
break;
case T_FIXNUM: {
char szD[128];
sprintf(szD, "%ld", FIX2LONG(v));
v = rb_cstr_convert_to_BigDecimal(szD, VpBaseFig() * 2 + 1, must);
break;
}
#ifdef ENABLE_NUMERIC_STRING
case T_STRING: {
const char *c_str = StringValueCStr(v);
v = rb_cstr_convert_to_BigDecimal(c_str, RSTRING_LEN(v) + VpBaseFig() + 1, must);
break;
}
#endif /* ENABLE_NUMERIC_STRING */
case T_BIGNUM: {
VALUE bg = rb_big2str(v, 10);
v = rb_cstr_convert_to_BigDecimal(RSTRING_PTR(bg), RSTRING_LEN(bg) + VpBaseFig() + 1, must);
RB_GC_GUARD(bg);
break;
}
default:
goto SomeOneMayDoIt;
}
Real *vp;
TypedData_Get_Struct(v, Real, &BigDecimal_data_type, vp);
return vp;
SomeOneMayDoIt:
if (must) {
cannot_be_coerced_into_BigDecimal(rb_eTypeError, v);
}
return NULL; /* NULL means to coerce */
}
static Real*
GetVpValue(VALUE v, int must)
{
return GetVpValueWithPrec(v, -1, must);
}
/* call-seq:
* BigDecimal.double_fig -> integer
*
* Returns the number of digits a Float object is allowed to have;
* the result is system-dependent:
*
* BigDecimal.double_fig # => 16
*
*/
static VALUE
BigDecimal_double_fig(VALUE self)
{
return INT2FIX(VpDblFig());
}
/* call-seq:
* precs -> array
*
* Returns an Array of two Integer values that represent platform-dependent
* internal storage properties.
*
* This method is deprecated and will be removed in the future.
* Instead, use BigDecimal#n_significant_digits for obtaining the number of
* significant digits in scientific notation, and BigDecimal#precision for
* obtaining the number of digits in decimal notation.
*
*/
static VALUE
BigDecimal_prec(VALUE self)
{
ENTER(1);
Real *p;
VALUE obj;
rb_category_warn(RB_WARN_CATEGORY_DEPRECATED,
"BigDecimal#precs is deprecated and will be removed in the future; "
"use BigDecimal#precision instead.");
GUARD_OBJ(p, GetVpValue(self, 1));
obj = rb_assoc_new(SIZET2NUM(p->Prec*VpBaseFig()),
SIZET2NUM(p->MaxPrec*VpBaseFig()));
return obj;
}
static void
BigDecimal_count_precision_and_scale(VALUE self, ssize_t *out_precision, ssize_t *out_scale)
{
ENTER(1);
if (out_precision == NULL && out_scale == NULL)
return;
Real *p;
GUARD_OBJ(p, GetVpValue(self, 1));
if (VpIsZero(p) || !VpIsDef(p)) {
zero:
if (out_precision) *out_precision = 0;
if (out_scale) *out_scale = 0;
return;
}
DECDIG x;
ssize_t n = p->Prec; /* The length of frac without zeros. */
while (n > 0 && p->frac[n-1] == 0) --n;
if (n == 0) goto zero;
int nlz = BASE_FIG;
for (x = p->frac[0]; x > 0; x /= 10) --nlz;
int ntz = 0;
for (x = p->frac[n-1]; x > 0 && x % 10 == 0; x /= 10) ++ntz;
/*
* Calculate the precision and the scale
* -------------------------------------
*
* The most significant digit is frac[0], and the least significant digit
* is frac[Prec-1]. When the exponent is zero, the decimal point is
* located just before frac[0].
*
* When the exponent is negative, the decimal point moves to leftward.
* In this case, the precision can be calculated by
*
* precision = BASE_FIG * (-exponent + n) - ntz,
*
* and the scale is the same as precision.
*
* 0 . 0000 0000 | frac[0] ... frac[n-1] |
* |<----------| exponent == -2 |
* |---------------------------------->| precision
* |---------------------------------->| scale
*
*
* Conversely, when the exponent is positive, the decimal point moves to
* rightward. In this case, the scale equals to
*
* BASE_FIG * (n - exponent) - ntz.
*
* the precision equals to
*
* scale + BASE_FIG * exponent - nlz.
*
* | frac[0] frac[1] . frac[2] ... frac[n-1] |
* |---------------->| exponent == 2 |
* | |---------------------->| scale
* |---------------------------------------->| precision
*/
ssize_t ex = p->exponent;
/* Count the number of decimal digits before frac[1]. */
ssize_t n_digits_head = BASE_FIG;
if (ex < 0) {
n_digits_head += (-ex) * BASE_FIG; /* The number of leading zeros before frac[0]. */
ex = 0;
}
else if (ex > 0) {
/* Count the number of decimal digits without the leading zeros in
* the most significant digit in the integral part.
*/
n_digits_head -= nlz; /* Make the number of digits */
}
if (out_precision) {
ssize_t precision = n_digits_head;
/* Count the number of decimal digits after frac[0]. */
if (ex > (ssize_t)n) {
/* In this case the number is an integer with some trailing zeros. */
precision += (ex - 1) * BASE_FIG;
}
else if (n > 0) {
precision += (n - 1) * BASE_FIG;
if (ex < (ssize_t)n) {
precision -= ntz;
}
}
*out_precision = precision;
}
if (out_scale) {
ssize_t scale = 0;
if (p->exponent < 0) {
scale = n_digits_head + (n - 1) * BASE_FIG - ntz;
}
else if (n > p->exponent) {
scale = (n - p->exponent) * BASE_FIG - ntz;
}
*out_scale = scale;
}
}
/*
* call-seq:
* precision -> integer
*
* Returns the number of decimal digits in +self+:
*
* BigDecimal("0").precision # => 0
* BigDecimal("1").precision # => 1
* BigDecimal("1.1").precision # => 2
* BigDecimal("3.1415").precision # => 5
* BigDecimal("-1e20").precision # => 21
* BigDecimal("1e-20").precision # => 20
* BigDecimal("Infinity").precision # => 0
* BigDecimal("-Infinity").precision # => 0
* BigDecimal("NaN").precision # => 0
*
*/
static VALUE
BigDecimal_precision(VALUE self)
{
ssize_t precision;
BigDecimal_count_precision_and_scale(self, &precision, NULL);
return SSIZET2NUM(precision);
}
/*
* call-seq:
* scale -> integer
*
* Returns the number of decimal digits following the decimal digits in +self+.
*
* BigDecimal("0").scale # => 0
* BigDecimal("1").scale # => 1
* BigDecimal("1.1").scale # => 1
* BigDecimal("3.1415").scale # => 4
* BigDecimal("-1e20").precision # => 0
* BigDecimal("1e-20").precision # => 20
* BigDecimal("Infinity").scale # => 0
* BigDecimal("-Infinity").scale # => 0
* BigDecimal("NaN").scale # => 0
*/
static VALUE
BigDecimal_scale(VALUE self)
{
ssize_t scale;
BigDecimal_count_precision_and_scale(self, NULL, &scale);
return SSIZET2NUM(scale);
}
/*
* call-seq:
* precision_scale -> [integer, integer]
*
* Returns a 2-length array; the first item is the result of
* BigDecimal#precision and the second one is of BigDecimal#scale.
*
* See BigDecimal#precision.
* See BigDecimal#scale.
*/
static VALUE
BigDecimal_precision_scale(VALUE self)
{
ssize_t precision, scale;
BigDecimal_count_precision_and_scale(self, &precision, &scale);
return rb_assoc_new(SSIZET2NUM(precision), SSIZET2NUM(scale));
}
/*
* call-seq:
* n_significant_digits -> integer
*
* Returns the number of decimal significant digits in +self+.
*
* BigDecimal("0").scale # => 0
* BigDecimal("1").scale # => 1
* BigDecimal("1.1").scale # => 2
* BigDecimal("3.1415").scale # => 5
* BigDecimal("-1e20").precision # => 1
* BigDecimal("1e-20").precision # => 1
* BigDecimal("Infinity").scale # => 0
* BigDecimal("-Infinity").scale # => 0
* BigDecimal("NaN").scale # => 0
*/
static VALUE
BigDecimal_n_significant_digits(VALUE self)
{
ENTER(1);
Real *p;
GUARD_OBJ(p, GetVpValue(self, 1));
if (VpIsZero(p) || !VpIsDef(p)) {
return INT2FIX(0);
}
ssize_t n = p->Prec; /* The length of frac without trailing zeros. */
for (n = p->Prec; n > 0 && p->frac[n-1] == 0; --n);
if (n == 0) return INT2FIX(0);
DECDIG x;
int nlz = BASE_FIG;
for (x = p->frac[0]; x > 0; x /= 10) --nlz;
int ntz = 0;
for (x = p->frac[n-1]; x > 0 && x % 10 == 0; x /= 10) ++ntz;
ssize_t n_significant_digits = BASE_FIG*n - nlz - ntz;
return SSIZET2NUM(n_significant_digits);
}
/*
* call-seq:
* hash -> integer
*
* Returns the integer hash value for +self+.
*
* Two instances of \BigDecimal have the same hash value if and only if
* they have equal:
*
* - Sign.
* - Fractional part.
* - Exponent.
*
*/
static VALUE
BigDecimal_hash(VALUE self)
{
ENTER(1);
Real *p;
st_index_t hash;
GUARD_OBJ(p, GetVpValue(self, 1));
hash = (st_index_t)p->sign;
/* hash!=2: the case for 0(1),NaN(0) or +-Infinity(3) is sign itself */
if(hash == 2 || hash == (st_index_t)-2) {
hash ^= rb_memhash(p->frac, sizeof(DECDIG)*p->Prec);
hash += p->exponent;
}
return ST2FIX(hash);
}
/*
* call-seq:
* _dump -> string
*
* Returns a string representing the marshalling of +self+.
* See module Marshal.
*
* inf = BigDecimal('Infinity') # => Infinity
* dumped = inf._dump # => "9:Infinity"
* BigDecimal._load(dumped) # => Infinity
*
*/
static VALUE
BigDecimal_dump(int argc, VALUE *argv, VALUE self)
{
ENTER(5);
Real *vp;
char *psz;
VALUE dummy;
volatile VALUE dump;
rb_scan_args(argc, argv, "01", &dummy);
GUARD_OBJ(vp,GetVpValue(self, 1));
dump = rb_str_new(0, VpNumOfChars(vp, "E")+50);
psz = RSTRING_PTR(dump);
sprintf(psz, "%"PRIuSIZE":", VpMaxPrec(vp)*VpBaseFig());
VpToString(vp, psz+strlen(psz), 0, 0);
rb_str_resize(dump, strlen(psz));
return dump;
}
/*
* Internal method used to provide marshalling support. See the Marshal module.
*/
static VALUE
BigDecimal_load(VALUE self, VALUE str)
{
ENTER(2);
Real *pv;
unsigned char *pch;
unsigned char ch;
unsigned long m=0;
pch = (unsigned char *)StringValueCStr(str);
/* First get max prec */
while((*pch) != (unsigned char)'\0' && (ch = *pch++) != (unsigned char)':') {
if(!ISDIGIT(ch)) {
rb_raise(rb_eTypeError, "load failed: invalid character in the marshaled string");
}
m = m*10 + (unsigned long)(ch-'0');
}
if (m > VpBaseFig()) m -= VpBaseFig();
GUARD_OBJ(pv, VpNewRbClass(m, (char *)pch, self, true, true));
m /= VpBaseFig();
if (m && pv->MaxPrec > m) {
pv->MaxPrec = m+1;
}
return VpCheckGetValue(pv);
}
static unsigned short
check_rounding_mode_option(VALUE const opts)
{
VALUE mode;
char const *s;
long l;
assert(RB_TYPE_P(opts, T_HASH));
if (NIL_P(opts))
goto noopt;
mode = rb_hash_lookup2(opts, ID2SYM(id_half), Qundef);
if (mode == Qundef || NIL_P(mode))
goto noopt;
if (SYMBOL_P(mode))
mode = rb_sym2str(mode);
else if (!RB_TYPE_P(mode, T_STRING)) {
VALUE str_mode = rb_check_string_type(mode);
if (NIL_P(str_mode)) goto invalid;
mode = str_mode;
}
s = RSTRING_PTR(mode);
l = RSTRING_LEN(mode);
switch (l) {
case 2:
if (strncasecmp(s, "up", 2) == 0)
return VP_ROUND_HALF_UP;
break;
case 4:
if (strncasecmp(s, "even", 4) == 0)
return VP_ROUND_HALF_EVEN;
else if (strncasecmp(s, "down", 4) == 0)
return VP_ROUND_HALF_DOWN;
break;
default:
break;
}
invalid:
if (NIL_P(mode))
rb_raise(rb_eArgError, "invalid rounding mode: nil");
else
rb_raise(rb_eArgError, "invalid rounding mode: %"PRIsVALUE, mode);
noopt:
return VpGetRoundMode();
}
static unsigned short
check_rounding_mode(VALUE const v)
{
unsigned short sw;
ID id;
switch (TYPE(v)) {
case T_SYMBOL:
id = SYM2ID(v);
if (id == id_up)
return VP_ROUND_UP;
if (id == id_down || id == id_truncate)
return VP_ROUND_DOWN;
if (id == id_half_up || id == id_default)
return VP_ROUND_HALF_UP;
if (id == id_half_down)
return VP_ROUND_HALF_DOWN;
if (id == id_half_even || id == id_banker)
return VP_ROUND_HALF_EVEN;
if (id == id_ceiling || id == id_ceil)
return VP_ROUND_CEIL;
if (id == id_floor)
return VP_ROUND_FLOOR;
rb_raise(rb_eArgError, "invalid rounding mode");
default:
break;
}
sw = NUM2USHORT(v);
if (!VpIsRoundMode(sw)) {
rb_raise(rb_eArgError, "invalid rounding mode");
}
return sw;
}
/* call-seq:
* BigDecimal.mode(mode, setting = nil) -> integer
*
* Returns an integer representing the mode settings
* for exception handling and rounding.
*
* These modes control exception handling:
*
* - \BigDecimal::EXCEPTION_NaN.
* - \BigDecimal::EXCEPTION_INFINITY.
* - \BigDecimal::EXCEPTION_UNDERFLOW.
* - \BigDecimal::EXCEPTION_OVERFLOW.
* - \BigDecimal::EXCEPTION_ZERODIVIDE.
* - \BigDecimal::EXCEPTION_ALL.
*
* Values for +setting+ for exception handling:
*
* - +true+: sets the given +mode+ to +true+.
* - +false+: sets the given +mode+ to +false+.
* - +nil+: does not modify the mode settings.
*
* You can use method BigDecimal.save_exception_mode
* to temporarily change, and then automatically restore, exception modes.
*
* For clarity, some examples below begin by setting all
* exception modes to +false+.
*
* This mode controls the way rounding is to be performed:
*
* - \BigDecimal::ROUND_MODE
*
* You can use method BigDecimal.save_rounding_mode
* to temporarily change, and then automatically restore, the rounding mode.
*
* <b>NaNs</b>
*
* Mode \BigDecimal::EXCEPTION_NaN controls behavior
* when a \BigDecimal NaN is created.
*
* Settings:
*
* - +false+ (default): Returns <tt>BigDecimal('NaN')</tt>.
* - +true+: Raises FloatDomainError.
*
* Examples:
*
* BigDecimal.mode(BigDecimal::EXCEPTION_ALL, false) # => 0
* BigDecimal('NaN') # => NaN
* BigDecimal.mode(BigDecimal::EXCEPTION_NaN, true) # => 2
* BigDecimal('NaN') # Raises FloatDomainError
*
* <b>Infinities</b>
*
* Mode \BigDecimal::EXCEPTION_INFINITY controls behavior
* when a \BigDecimal Infinity or -Infinity is created.
* Settings:
*
* - +false+ (default): Returns <tt>BigDecimal('Infinity')</tt>
* or <tt>BigDecimal('-Infinity')</tt>.
* - +true+: Raises FloatDomainError.
*
* Examples:
*
* BigDecimal.mode(BigDecimal::EXCEPTION_ALL, false) # => 0
* BigDecimal('Infinity') # => Infinity
* BigDecimal('-Infinity') # => -Infinity
* BigDecimal.mode(BigDecimal::EXCEPTION_INFINITY, true) # => 1
* BigDecimal('Infinity') # Raises FloatDomainError
* BigDecimal('-Infinity') # Raises FloatDomainError
*
* <b>Underflow</b>
*
* Mode \BigDecimal::EXCEPTION_UNDERFLOW controls behavior
* when a \BigDecimal underflow occurs.
* Settings:
*
* - +false+ (default): Returns <tt>BigDecimal('0')</tt>
* or <tt>BigDecimal('-Infinity')</tt>.
* - +true+: Raises FloatDomainError.
*
* Examples:
*
* BigDecimal.mode(BigDecimal::EXCEPTION_ALL, false) # => 0
* def flow_under
* x = BigDecimal('0.1')
* 100.times { x *= x }
* end
* flow_under # => 100
* BigDecimal.mode(BigDecimal::EXCEPTION_UNDERFLOW, true) # => 4
* flow_under # Raises FloatDomainError
*
* <b>Overflow</b>
*
* Mode \BigDecimal::EXCEPTION_OVERFLOW controls behavior
* when a \BigDecimal overflow occurs.
* Settings:
*
* - +false+ (default): Returns <tt>BigDecimal('Infinity')</tt>
* or <tt>BigDecimal('-Infinity')</tt>.
* - +true+: Raises FloatDomainError.
*
* Examples:
*
* BigDecimal.mode(BigDecimal::EXCEPTION_ALL, false) # => 0
* def flow_over
* x = BigDecimal('10')
* 100.times { x *= x }
* end
* flow_over # => 100
* BigDecimal.mode(BigDecimal::EXCEPTION_OVERFLOW, true) # => 1
* flow_over # Raises FloatDomainError
*
* <b>Zero Division</b>
*
* Mode \BigDecimal::EXCEPTION_ZERODIVIDE controls behavior
* when a zero-division occurs.
* Settings:
*
* - +false+ (default): Returns <tt>BigDecimal('Infinity')</tt>
* or <tt>BigDecimal('-Infinity')</tt>.
* - +true+: Raises FloatDomainError.
*
* Examples:
*
* BigDecimal.mode(BigDecimal::EXCEPTION_ALL, false) # => 0
* one = BigDecimal('1')
* zero = BigDecimal('0')
* one / zero # => Infinity
* BigDecimal.mode(BigDecimal::EXCEPTION_ZERODIVIDE, true) # => 16
* one / zero # Raises FloatDomainError
*
* <b>All Exceptions</b>
*
* Mode \BigDecimal::EXCEPTION_ALL controls all of the above:
*
* BigDecimal.mode(BigDecimal::EXCEPTION_ALL, false) # => 0
* BigDecimal.mode(BigDecimal::EXCEPTION_ALL, true) # => 23
*
* <b>Rounding</b>
*
* Mode \BigDecimal::ROUND_MODE controls the way rounding is to be performed;
* its +setting+ values are:
*
* - +ROUND_UP+: Round away from zero.
* Aliased as +:up+.
* - +ROUND_DOWN+: Round toward zero.
* Aliased as +:down+ and +:truncate+.
* - +ROUND_HALF_UP+: Round toward the nearest neighbor;
* if the neighbors are equidistant, round away from zero.
* Aliased as +:half_up+ and +:default+.
* - +ROUND_HALF_DOWN+: Round toward the nearest neighbor;
* if the neighbors are equidistant, round toward zero.
* Aliased as +:half_down+.
* - +ROUND_HALF_EVEN+ (Banker's rounding): Round toward the nearest neighbor;
* if the neighbors are equidistant, round toward the even neighbor.
* Aliased as +:half_even+ and +:banker+.
* - +ROUND_CEILING+: Round toward positive infinity.
* Aliased as +:ceiling+ and +:ceil+.
* - +ROUND_FLOOR+: Round toward negative infinity.
* Aliased as +:floor:+.
*
*/
static VALUE
BigDecimal_mode(int argc, VALUE *argv, VALUE self)
{
VALUE which;
VALUE val;
unsigned long f,fo;
rb_scan_args(argc, argv, "11", &which, &val);
f = (unsigned long)NUM2INT(which);
if (f & VP_EXCEPTION_ALL) {
/* Exception mode setting */
fo = VpGetException();
if (val == Qnil) return INT2FIX(fo);
if (val != Qfalse && val!=Qtrue) {
rb_raise(rb_eArgError, "second argument must be true or false");
return Qnil; /* Not reached */
}
if (f & VP_EXCEPTION_INFINITY) {
VpSetException((unsigned short)((val == Qtrue) ? (fo | VP_EXCEPTION_INFINITY) :
(fo & (~VP_EXCEPTION_INFINITY))));
}
fo = VpGetException();
if (f & VP_EXCEPTION_NaN) {
VpSetException((unsigned short)((val == Qtrue) ? (fo | VP_EXCEPTION_NaN) :
(fo & (~VP_EXCEPTION_NaN))));
}
fo = VpGetException();
if (f & VP_EXCEPTION_UNDERFLOW) {
VpSetException((unsigned short)((val == Qtrue) ? (fo | VP_EXCEPTION_UNDERFLOW) :
(fo & (~VP_EXCEPTION_UNDERFLOW))));
}
fo = VpGetException();
if(f & VP_EXCEPTION_ZERODIVIDE) {
VpSetException((unsigned short)((val == Qtrue) ? (fo | VP_EXCEPTION_ZERODIVIDE) :
(fo & (~VP_EXCEPTION_ZERODIVIDE))));
}
fo = VpGetException();
return INT2FIX(fo);
}
if (VP_ROUND_MODE == f) {
/* Rounding mode setting */
unsigned short sw;
fo = VpGetRoundMode();
if (NIL_P(val)) return INT2FIX(fo);
sw = check_rounding_mode(val);
fo = VpSetRoundMode(sw);
return INT2FIX(fo);
}
rb_raise(rb_eTypeError, "first argument for BigDecimal.mode invalid");
return Qnil;
}
static size_t
GetAddSubPrec(Real *a, Real *b)
{
size_t mxs;
size_t mx = a->Prec;
SIGNED_VALUE d;
if (!VpIsDef(a) || !VpIsDef(b)) return (size_t)-1L;
if (mx < b->Prec) mx = b->Prec;
if (a->exponent != b->exponent) {
mxs = mx;
d = a->exponent - b->exponent;
if (d < 0) d = -d;
mx = mx + (size_t)d;
if (mx < mxs) {
return VpException(VP_EXCEPTION_INFINITY, "Exponent overflow", 0);
}
}
return mx;
}
static SIGNED_VALUE
GetPrecisionInt(VALUE v)
{
SIGNED_VALUE n;
n = NUM2INT(v);
if (n < 0) {
rb_raise(rb_eArgError, "negative precision");
}
return n;
}
static VALUE
BigDecimal_wrap_struct(VALUE obj, Real *vp)
{
assert(is_kind_of_BigDecimal(obj));
assert(vp != NULL);
if (vp->obj == obj && RTYPEDDATA_DATA(obj) == vp)
return obj;
assert(RTYPEDDATA_DATA(obj) == NULL);
assert(vp->obj == 0);
RTYPEDDATA_DATA(obj) = vp;
vp->obj = obj;
RB_OBJ_FREEZE(obj);
return obj;
}
VP_EXPORT Real *
VpNewRbClass(size_t mx, const char *str, VALUE klass, bool strict_p, bool raise_exception)
{
VALUE obj = TypedData_Wrap_Struct(klass, &BigDecimal_data_type, 0);
Real *pv = VpAlloc(mx, str, strict_p, raise_exception);
if (!pv)
return NULL;
BigDecimal_wrap_struct(obj, pv);
return pv;
}
VP_EXPORT Real *
VpCreateRbObject(size_t mx, const char *str, bool raise_exception)
{
return VpNewRbClass(mx, str, rb_cBigDecimal, true, raise_exception);
}
#define VpAllocReal(prec) (Real *)VpMemAlloc(offsetof(Real, frac) + (prec) * sizeof(DECDIG))
static Real *
VpReallocReal(Real *pv, size_t prec)
{
VALUE obj = pv ? pv->obj : 0;
Real *new_pv = (Real *)VpMemRealloc(pv, offsetof(Real, frac) + prec * sizeof(DECDIG));
if (obj) {
new_pv->obj = 0;
BigDecimal_wrap_struct(obj, new_pv);
}
return new_pv;
}
static Real *
VpCopy(Real *pv, Real const* const x)
{
assert(x != NULL);
pv = VpReallocReal(pv, x->MaxPrec);
pv->MaxPrec = x->MaxPrec;
pv->Prec = x->Prec;
pv->exponent = x->exponent;
pv->sign = x->sign;
pv->flag = x->flag;
MEMCPY(pv->frac, x->frac, DECDIG, pv->MaxPrec);
return pv;
}
/* Returns True if the value is Not a Number. */
static VALUE
BigDecimal_IsNaN(VALUE self)
{
Real *p = GetVpValue(self, 1);
if (VpIsNaN(p)) return Qtrue;
return Qfalse;
}
/* Returns nil, -1, or +1 depending on whether the value is finite,
* -Infinity, or +Infinity.
*/
static VALUE
BigDecimal_IsInfinite(VALUE self)
{
Real *p = GetVpValue(self, 1);
if (VpIsPosInf(p)) return INT2FIX(1);
if (VpIsNegInf(p)) return INT2FIX(-1);
return Qnil;
}
/* Returns True if the value is finite (not NaN or infinite). */
static VALUE
BigDecimal_IsFinite(VALUE self)
{
Real *p = GetVpValue(self, 1);
if (VpIsNaN(p)) return Qfalse;
if (VpIsInf(p)) return Qfalse;
return Qtrue;
}
static void
BigDecimal_check_num(Real *p)
{
VpCheckException(p, true);
}
static VALUE BigDecimal_split(VALUE self);
/* Returns the value as an Integer.
*
* If the BigDecimal is infinity or NaN, raises FloatDomainError.
*/
static VALUE
BigDecimal_to_i(VALUE self)
{
ENTER(5);
ssize_t e, nf;
Real *p;
GUARD_OBJ(p, GetVpValue(self, 1));
BigDecimal_check_num(p);
e = VpExponent10(p);
if (e <= 0) return INT2FIX(0);
nf = VpBaseFig();
if (e <= nf) {
return LONG2NUM((long)(VpGetSign(p) * (DECDIG_DBL_SIGNED)p->frac[0]));
}
else {
VALUE a = BigDecimal_split(self);
VALUE digits = RARRAY_AREF(a, 1);
VALUE numerator = rb_funcall(digits, rb_intern("to_i"), 0);
VALUE ret;
ssize_t dpower = e - (ssize_t)RSTRING_LEN(digits);
if (BIGDECIMAL_NEGATIVE_P(p)) {
numerator = rb_funcall(numerator, '*', 1, INT2FIX(-1));
}
if (dpower < 0) {
ret = rb_funcall(numerator, rb_intern("div"), 1,
rb_funcall(INT2FIX(10), rb_intern("**"), 1,
INT2FIX(-dpower)));
}
else {
ret = rb_funcall(numerator, '*', 1,
rb_funcall(INT2FIX(10), rb_intern("**"), 1,
INT2FIX(dpower)));
}
if (RB_TYPE_P(ret, T_FLOAT)) {
rb_raise(rb_eFloatDomainError, "Infinity");
}
return ret;
}
}
/* Returns a new Float object having approximately the same value as the
* BigDecimal number. Normal accuracy limits and built-in errors of binary
* Float arithmetic apply.
*/
static VALUE
BigDecimal_to_f(VALUE self)
{
ENTER(1);
Real *p;
double d;
SIGNED_VALUE e;
char *buf;
volatile VALUE str;
GUARD_OBJ(p, GetVpValue(self, 1));
if (VpVtoD(&d, &e, p) != 1)
return rb_float_new(d);
if (e > (SIGNED_VALUE)(DBL_MAX_10_EXP+BASE_FIG))
goto overflow;
if (e < (SIGNED_VALUE)(DBL_MIN_10_EXP-BASE_FIG))
goto underflow;
str = rb_str_new(0, VpNumOfChars(p, "E"));
buf = RSTRING_PTR(str);
VpToString(p, buf, 0, 0);
errno = 0;
d = strtod(buf, 0);
if (errno == ERANGE) {
if (d == 0.0) goto underflow;
if (fabs(d) >= HUGE_VAL) goto overflow;
}
return rb_float_new(d);
overflow:
VpException(VP_EXCEPTION_OVERFLOW, "BigDecimal to Float conversion", 0);
if (BIGDECIMAL_NEGATIVE_P(p))
return rb_float_new(VpGetDoubleNegInf());
else
return rb_float_new(VpGetDoublePosInf());
underflow:
VpException(VP_EXCEPTION_UNDERFLOW, "BigDecimal to Float conversion", 0);
if (BIGDECIMAL_NEGATIVE_P(p))
return rb_float_new(-0.0);
else
return rb_float_new(0.0);
}
/* Converts a BigDecimal to a Rational.
*/
static VALUE
BigDecimal_to_r(VALUE self)
{
Real *p;
ssize_t sign, power, denomi_power;
VALUE a, digits, numerator;
p = GetVpValue(self, 1);
BigDecimal_check_num(p);
sign = VpGetSign(p);
power = VpExponent10(p);
a = BigDecimal_split(self);
digits = RARRAY_AREF(a, 1);
denomi_power = power - RSTRING_LEN(digits);
numerator = rb_funcall(digits, rb_intern("to_i"), 0);
if (sign < 0) {
numerator = rb_funcall(numerator, '*', 1, INT2FIX(-1));
}
if (denomi_power < 0) {
return rb_Rational(numerator,
rb_funcall(INT2FIX(10), rb_intern("**"), 1,
INT2FIX(-denomi_power)));
}
else {
return rb_Rational1(rb_funcall(numerator, '*', 1,
rb_funcall(INT2FIX(10), rb_intern("**"), 1,
INT2FIX(denomi_power))));
}
}
/* The coerce method provides support for Ruby type coercion. It is not
* enabled by default.
*
* This means that binary operations like + * / or - can often be performed
* on a BigDecimal and an object of another type, if the other object can
* be coerced into a BigDecimal value.
*
* e.g.
* a = BigDecimal("1.0")
* b = a / 2.0 #=> 0.5
*
* Note that coercing a String to a BigDecimal is not supported by default;
* it requires a special compile-time option when building Ruby.
*/
static VALUE
BigDecimal_coerce(VALUE self, VALUE other)
{
ENTER(2);
VALUE obj;
Real *b;
if (RB_TYPE_P(other, T_FLOAT)) {
GUARD_OBJ(b, GetVpValueWithPrec(other, 0, 1));
obj = rb_assoc_new(VpCheckGetValue(b), self);
}
else {
if (RB_TYPE_P(other, T_RATIONAL)) {
Real* pv = DATA_PTR(self);
GUARD_OBJ(b, GetVpValueWithPrec(other, pv->Prec*VpBaseFig(), 1));
}
else {
GUARD_OBJ(b, GetVpValue(other, 1));
}
obj = rb_assoc_new(b->obj, self);
}
return obj;
}
/*
* call-seq:
* +big_decimal -> self
*
* Returns +self+:
*
* +BigDecimal(5) # => 0.5e1
* +BigDecimal(-5) # => -0.5e1
*
*/
static VALUE
BigDecimal_uplus(VALUE self)
{
return self;
}
/*
* call-seq:
* self + value -> bigdecimal
*
* Returns the \BigDecimal sum of +self+ and +value+:
*
* b = BigDecimal('111111.111') # => 0.111111111e6
* b + 2 # => 0.111113111e6
* b + 2.0 # => 0.111113111e6
* b + Rational(2, 1) # => 0.111113111e6
* b + Complex(2, 0) # => (0.111113111e6+0i)
*
* See the {Note About Precision}[BigDecimal.html#class-BigDecimal-label-A+Note+About+Precision].
*
*/
static VALUE
BigDecimal_add(VALUE self, VALUE r)
{
ENTER(5);
Real *c, *a, *b;
size_t mx;
GUARD_OBJ(a, GetVpValue(self, 1));
if (RB_TYPE_P(r, T_FLOAT)) {
b = GetVpValueWithPrec(r, 0, 1);
}
else if (RB_TYPE_P(r, T_RATIONAL)) {
b = GetVpValueWithPrec(r, a->Prec*VpBaseFig(), 1);
}
else {
b = GetVpValue(r, 0);
}
if (!b) return DoSomeOne(self,r,'+');
SAVE(b);
if (VpIsNaN(b)) return b->obj;
if (VpIsNaN(a)) return a->obj;
mx = GetAddSubPrec(a, b);
if (mx == (size_t)-1L) {
GUARD_OBJ(c, VpCreateRbObject(VpBaseFig() + 1, "0", true));
VpAddSub(c, a, b, 1);
}
else {
GUARD_OBJ(c, VpCreateRbObject(mx * (VpBaseFig() + 1), "0", true));
if(!mx) {
VpSetInf(c, VpGetSign(a));
}
else {
VpAddSub(c, a, b, 1);
}
}
return VpCheckGetValue(c);
}
/* call-seq:
* self - value -> bigdecimal
*
* Returns the \BigDecimal difference of +self+ and +value+:
*
* b = BigDecimal('333333.333') # => 0.333333333e6
* b - 2 # => 0.333331333e6
* b - 2.0 # => 0.333331333e6
* b - Rational(2, 1) # => 0.333331333e6
* b - Complex(2, 0) # => (0.333331333e6+0i)
*
* See the {Note About Precision}[BigDecimal.html#class-BigDecimal-label-A+Note+About+Precision].
*
*/
static VALUE
BigDecimal_sub(VALUE self, VALUE r)
{
ENTER(5);
Real *c, *a, *b;
size_t mx;
GUARD_OBJ(a, GetVpValue(self,1));
if (RB_TYPE_P(r, T_FLOAT)) {
b = GetVpValueWithPrec(r, 0, 1);
}
else if (RB_TYPE_P(r, T_RATIONAL)) {
b = GetVpValueWithPrec(r, a->Prec*VpBaseFig(), 1);
}
else {
b = GetVpValue(r,0);
}
if (!b) return DoSomeOne(self,r,'-');
SAVE(b);
if (VpIsNaN(b)) return b->obj;
if (VpIsNaN(a)) return a->obj;
mx = GetAddSubPrec(a,b);
if (mx == (size_t)-1L) {
GUARD_OBJ(c, VpCreateRbObject(VpBaseFig() + 1, "0", true));
VpAddSub(c, a, b, -1);
}
else {
GUARD_OBJ(c,VpCreateRbObject(mx *(VpBaseFig() + 1), "0", true));
if (!mx) {
VpSetInf(c,VpGetSign(a));
}
else {
VpAddSub(c, a, b, -1);
}
}
return VpCheckGetValue(c);
}
static VALUE
BigDecimalCmp(VALUE self, VALUE r,char op)
{
ENTER(5);
SIGNED_VALUE e;
Real *a, *b=0;
GUARD_OBJ(a, GetVpValue(self, 1));
switch (TYPE(r)) {
case T_DATA:
if (!is_kind_of_BigDecimal(r)) break;
/* fall through */
case T_FIXNUM:
/* fall through */
case T_BIGNUM:
GUARD_OBJ(b, GetVpValue(r, 0));
break;
case T_FLOAT:
GUARD_OBJ(b, GetVpValueWithPrec(r, 0, 0));
break;
case T_RATIONAL:
GUARD_OBJ(b, GetVpValueWithPrec(r, a->Prec*VpBaseFig(), 0));
break;
default:
break;
}
if (b == NULL) {
ID f = 0;
switch (op) {
case '*':
return rb_num_coerce_cmp(self, r, rb_intern("<=>"));
case '=':
return RTEST(rb_num_coerce_cmp(self, r, rb_intern("=="))) ? Qtrue : Qfalse;
case 'G':
f = rb_intern(">=");
break;
case 'L':
f = rb_intern("<=");
break;
case '>':
/* fall through */
case '<':
f = (ID)op;
break;
default:
break;
}
return rb_num_coerce_relop(self, r, f);
}
SAVE(b);
e = VpComp(a, b);
if (e == 999)
return (op == '*') ? Qnil : Qfalse;
switch (op) {
case '*':
return INT2FIX(e); /* any op */
case '=':
if (e == 0) return Qtrue;
return Qfalse;
case 'G':
if (e >= 0) return Qtrue;
return Qfalse;
case '>':
if (e > 0) return Qtrue;
return Qfalse;
case 'L':
if (e <= 0) return Qtrue;
return Qfalse;
case '<':
if (e < 0) return Qtrue;
return Qfalse;
default:
break;
}
rb_bug("Undefined operation in BigDecimalCmp()");
UNREACHABLE;
}
/* Returns True if the value is zero. */
static VALUE
BigDecimal_zero(VALUE self)
{
Real *a = GetVpValue(self, 1);
return VpIsZero(a) ? Qtrue : Qfalse;
}
/* Returns self if the value is non-zero, nil otherwise. */
static VALUE
BigDecimal_nonzero(VALUE self)
{
Real *a = GetVpValue(self, 1);
return VpIsZero(a) ? Qnil : self;
}
/* The comparison operator.
* a <=> b is 0 if a == b, 1 if a > b, -1 if a < b.
*/
static VALUE
BigDecimal_comp(VALUE self, VALUE r)
{
return BigDecimalCmp(self, r, '*');
}
/*
* Tests for value equality; returns true if the values are equal.
*
* The == and === operators and the eql? method have the same implementation
* for BigDecimal.
*
* Values may be coerced to perform the comparison:
*
* BigDecimal('1.0') == 1.0 #=> true
*/
static VALUE
BigDecimal_eq(VALUE self, VALUE r)
{
return BigDecimalCmp(self, r, '=');
}
/* call-seq:
* self < other -> true or false
*
* Returns +true+ if +self+ is less than +other+, +false+ otherwise:
*
* b = BigDecimal('1.5') # => 0.15e1
* b < 2 # => true
* b < 2.0 # => true
* b < Rational(2, 1) # => true
* b < 1.5 # => false
*
* Raises an exception if the comparison cannot be made.
*
*/
static VALUE
BigDecimal_lt(VALUE self, VALUE r)
{
return BigDecimalCmp(self, r, '<');
}
/* call-seq:
* self <= other -> true or false
*
* Returns +true+ if +self+ is less or equal to than +other+, +false+ otherwise:
*
* b = BigDecimal('1.5') # => 0.15e1
* b <= 2 # => true
* b <= 2.0 # => true
* b <= Rational(2, 1) # => true
* b <= 1.5 # => true
* b < 1 # => false
*
* Raises an exception if the comparison cannot be made.
*
*/
static VALUE
BigDecimal_le(VALUE self, VALUE r)
{
return BigDecimalCmp(self, r, 'L');
}
/* call-seq:
* self > other -> true or false
*
* Returns +true+ if +self+ is greater than +other+, +false+ otherwise:
*
* b = BigDecimal('1.5')
* b > 1 # => true
* b > 1.0 # => true
* b > Rational(1, 1) # => true
* b > 2 # => false
*
* Raises an exception if the comparison cannot be made.
*
*/
static VALUE
BigDecimal_gt(VALUE self, VALUE r)
{
return BigDecimalCmp(self, r, '>');
}
/* call-seq:
* self >= other -> true or false
*
* Returns +true+ if +self+ is greater than or equal to +other+, +false+ otherwise:
*
* b = BigDecimal('1.5')
* b >= 1 # => true
* b >= 1.0 # => true
* b >= Rational(1, 1) # => true
* b >= 1.5 # => true
* b > 2 # => false
*
* Raises an exception if the comparison cannot be made.
*
*/
static VALUE
BigDecimal_ge(VALUE self, VALUE r)
{
return BigDecimalCmp(self, r, 'G');
}
/*
* call-seq:
* -self -> bigdecimal
*
* Returns the \BigDecimal negation of self:
*
* b0 = BigDecimal('1.5')
* b1 = -b0 # => -0.15e1
* b2 = -b1 # => 0.15e1
*
*/
static VALUE
BigDecimal_neg(VALUE self)
{
ENTER(5);
Real *c, *a;
GUARD_OBJ(a, GetVpValue(self, 1));
GUARD_OBJ(c, VpCreateRbObject(a->Prec *(VpBaseFig() + 1), "0", true));
VpAsgn(c, a, -1);
return VpCheckGetValue(c);
}
static VALUE
BigDecimal_mult(VALUE self, VALUE r)
{
ENTER(5);
Real *c, *a, *b;
size_t mx;
GUARD_OBJ(a, GetVpValue(self, 1));
if (RB_TYPE_P(r, T_FLOAT)) {
b = GetVpValueWithPrec(r, 0, 1);
}
else if (RB_TYPE_P(r, T_RATIONAL)) {
b = GetVpValueWithPrec(r, a->Prec*VpBaseFig(), 1);
}
else {
b = GetVpValue(r,0);
}
if (!b) return DoSomeOne(self, r, '*');
SAVE(b);
mx = a->Prec + b->Prec;
GUARD_OBJ(c, VpCreateRbObject(mx *(VpBaseFig() + 1), "0", true));
VpMult(c, a, b);
return VpCheckGetValue(c);
}
static VALUE
BigDecimal_divide(VALUE self, VALUE r, Real **c, Real **res, Real **div)
/* For c = self.div(r): with round operation */
{
ENTER(5);
Real *a, *b;
ssize_t a_prec, b_prec;
size_t mx;
TypedData_Get_Struct(self, Real, &BigDecimal_data_type, a);
SAVE(a);
VALUE rr = r;
if (is_kind_of_BigDecimal(rr)) {
/* do nothing */
}
else if (RB_INTEGER_TYPE_P(r)) {
rr = rb_inum_convert_to_BigDecimal(r, 0, true);
}
else if (RB_TYPE_P(r, T_FLOAT)) {
rr = rb_float_convert_to_BigDecimal(r, 0, true);
}
else if (RB_TYPE_P(r, T_RATIONAL)) {
rr = rb_rational_convert_to_BigDecimal(r, a->Prec*BASE_FIG, true);
}
if (!is_kind_of_BigDecimal(rr)) {
return DoSomeOne(self, r, '/');
}
TypedData_Get_Struct(rr, Real, &BigDecimal_data_type, b);
SAVE(b);
*div = b;
BigDecimal_count_precision_and_scale(self, &a_prec, NULL);
BigDecimal_count_precision_and_scale(rr, &b_prec, NULL);
mx = (a_prec > b_prec) ? a_prec : b_prec;
mx *= 2;
if (2*BIGDECIMAL_DOUBLE_FIGURES > mx)
mx = 2*BIGDECIMAL_DOUBLE_FIGURES;
GUARD_OBJ((*c), VpCreateRbObject(mx + 2*BASE_FIG, "#0", true));
GUARD_OBJ((*res), VpCreateRbObject((mx + 1)*2 + 2*BASE_FIG, "#0", true));
VpDivd(*c, *res, a, b);
return Qnil;
}
static VALUE BigDecimal_DoDivmod(VALUE self, VALUE r, Real **div, Real **mod);
/* call-seq:
* a / b -> bigdecimal
*
* Divide by the specified value.
*
* The result precision will be the precision of the larger operand,
* but its minimum is 2*Float::DIG.
*
* See BigDecimal#div.
* See BigDecimal#quo.
*/
static VALUE
BigDecimal_div(VALUE self, VALUE r)
/* For c = self/r: with round operation */
{
ENTER(5);
Real *c=NULL, *res=NULL, *div = NULL;
r = BigDecimal_divide(self, r, &c, &res, &div);
if (!NIL_P(r)) return r; /* coerced by other */
SAVE(c); SAVE(res); SAVE(div);
/* a/b = c + r/b */
/* c xxxxx
r 00000yyyyy ==> (y/b)*BASE >= HALF_BASE
*/
/* Round */
if (VpHasVal(div)) { /* frac[0] must be zero for NaN,INF,Zero */
VpInternalRound(c, 0, c->frac[c->Prec-1], (DECDIG)(VpBaseVal() * (DECDIG_DBL)res->frac[0] / div->frac[0]));
}
return VpCheckGetValue(c);
}
static VALUE BigDecimal_round(int argc, VALUE *argv, VALUE self);
/* call-seq:
* quo(value) -> bigdecimal
* quo(value, digits) -> bigdecimal
*
* Divide by the specified value.
*
* digits:: If specified and less than the number of significant digits of
* the result, the result is rounded to the given number of digits,
* according to the rounding mode indicated by BigDecimal.mode.
*
* If digits is 0 or omitted, the result is the same as for the
* / operator.
*
* See BigDecimal#/.
* See BigDecimal#div.
*/
static VALUE
BigDecimal_quo(int argc, VALUE *argv, VALUE self)
{
VALUE value, digits, result;
SIGNED_VALUE n = -1;
argc = rb_scan_args(argc, argv, "11", &value, &digits);
if (argc > 1) {
n = GetPrecisionInt(digits);
}
if (n > 0) {
result = BigDecimal_div2(self, value, digits);
}
else {
result = BigDecimal_div(self, value);
}
return result;
}
/*
* %: mod = a%b = a - (a.to_f/b).floor * b
* div = (a.to_f/b).floor
*/
static VALUE
BigDecimal_DoDivmod(VALUE self, VALUE r, Real **div, Real **mod)
{
ENTER(8);
Real *c=NULL, *d=NULL, *res=NULL;
Real *a, *b;
ssize_t a_prec, b_prec;
size_t mx;
TypedData_Get_Struct(self, Real, &BigDecimal_data_type, a);
SAVE(a);
VALUE rr = r;
if (is_kind_of_BigDecimal(rr)) {
/* do nothing */
}
else if (RB_INTEGER_TYPE_P(r)) {
rr = rb_inum_convert_to_BigDecimal(r, 0, true);
}
else if (RB_TYPE_P(r, T_FLOAT)) {
rr = rb_float_convert_to_BigDecimal(r, 0, true);
}
else if (RB_TYPE_P(r, T_RATIONAL)) {
rr = rb_rational_convert_to_BigDecimal(r, a->Prec*BASE_FIG, true);
}
if (!is_kind_of_BigDecimal(rr)) {
return Qfalse;
}
TypedData_Get_Struct(rr, Real, &BigDecimal_data_type, b);
SAVE(b);
if (VpIsNaN(a) || VpIsNaN(b)) goto NaN;
if (VpIsInf(a) && VpIsInf(b)) goto NaN;
if (VpIsZero(b)) {
rb_raise(rb_eZeroDivError, "divided by 0");
}
if (VpIsInf(a)) {
if (VpGetSign(a) == VpGetSign(b)) {
VALUE inf = BigDecimal_positive_infinity();
TypedData_Get_Struct(inf, Real, &BigDecimal_data_type, *div);
}
else {
VALUE inf = BigDecimal_negative_infinity();
TypedData_Get_Struct(inf, Real, &BigDecimal_data_type, *div);
}
VALUE nan = BigDecimal_nan();
TypedData_Get_Struct(nan, Real, &BigDecimal_data_type, *mod);
return Qtrue;
}
if (VpIsInf(b)) {
VALUE zero = BigDecimal_positive_zero();
TypedData_Get_Struct(zero, Real, &BigDecimal_data_type, *div);
*mod = a;
return Qtrue;
}
if (VpIsZero(a)) {
VALUE zero = BigDecimal_positive_zero();
TypedData_Get_Struct(zero, Real, &BigDecimal_data_type, *div);
TypedData_Get_Struct(zero, Real, &BigDecimal_data_type, *mod);
return Qtrue;
}
BigDecimal_count_precision_and_scale(self, &a_prec, NULL);
BigDecimal_count_precision_and_scale(rr, &b_prec, NULL);
mx = (a_prec > b_prec) ? a_prec : b_prec;
mx *= 2;
if (2*BIGDECIMAL_DOUBLE_FIGURES > mx)
mx = 2*BIGDECIMAL_DOUBLE_FIGURES;
GUARD_OBJ(c, VpCreateRbObject(mx + 2*BASE_FIG, "0", true));
GUARD_OBJ(res, VpCreateRbObject(mx*2 + 2*BASE_FIG, "#0", true));
VpDivd(c, res, a, b);
mx = c->Prec * BASE_FIG;
GUARD_OBJ(d, VpCreateRbObject(mx, "0", true));
VpActiveRound(d, c, VP_ROUND_DOWN, 0);
VpMult(res, d, b);
VpAddSub(c, a, res, -1);
if (!VpIsZero(c) && (VpGetSign(a) * VpGetSign(b) < 0)) {
/* result adjustment for negative case */
res = VpReallocReal(res, d->MaxPrec);
res->MaxPrec = d->MaxPrec;
VpAddSub(res, d, VpOne(), -1);
GUARD_OBJ(d, VpCreateRbObject(GetAddSubPrec(c, b) * 2*BASE_FIG, "0", true));
VpAddSub(d, c, b, 1);
*div = res;
*mod = d;
}
else {
*div = d;
*mod = c;
}
return Qtrue;
NaN:
{
VALUE nan = BigDecimal_nan();
TypedData_Get_Struct(nan, Real, &BigDecimal_data_type, *div);
TypedData_Get_Struct(nan, Real, &BigDecimal_data_type, *mod);
}
return Qtrue;
}
/* call-seq:
* a % b
* a.modulo(b)
*
* Returns the modulus from dividing by b.
*
* See BigDecimal#divmod.
*/
static VALUE
BigDecimal_mod(VALUE self, VALUE r) /* %: a%b = a - (a.to_f/b).floor * b */
{
ENTER(3);
Real *div = NULL, *mod = NULL;
if (BigDecimal_DoDivmod(self, r, &div, &mod)) {
SAVE(div); SAVE(mod);
return VpCheckGetValue(mod);
}
return DoSomeOne(self, r, '%');
}
static VALUE
BigDecimal_divremain(VALUE self, VALUE r, Real **dv, Real **rv)
{
ENTER(10);
size_t mx;
Real *a = NULL, *b = NULL, *c = NULL, *res = NULL, *d = NULL, *rr = NULL, *ff = NULL;
Real *f = NULL;
GUARD_OBJ(a, GetVpValue(self, 1));
if (RB_TYPE_P(r, T_FLOAT)) {
b = GetVpValueWithPrec(r, 0, 1);
}
else if (RB_TYPE_P(r, T_RATIONAL)) {
b = GetVpValueWithPrec(r, a->Prec*VpBaseFig(), 1);
}
else {
b = GetVpValue(r, 0);
}
if (!b) return DoSomeOne(self, r, rb_intern("remainder"));
SAVE(b);
mx = (a->MaxPrec + b->MaxPrec) *VpBaseFig();
GUARD_OBJ(c, VpCreateRbObject(mx, "0", true));
GUARD_OBJ(res, VpCreateRbObject((mx+1) * 2 + (VpBaseFig() + 1), "#0", true));
GUARD_OBJ(rr, VpCreateRbObject((mx+1) * 2 + (VpBaseFig() + 1), "#0", true));
GUARD_OBJ(ff, VpCreateRbObject((mx+1) * 2 + (VpBaseFig() + 1), "#0", true));
VpDivd(c, res, a, b);
mx = c->Prec *(VpBaseFig() + 1);
GUARD_OBJ(d, VpCreateRbObject(mx, "0", true));
GUARD_OBJ(f, VpCreateRbObject(mx, "0", true));
VpActiveRound(d, c, VP_ROUND_DOWN, 0); /* 0: round off */
VpFrac(f, c);
VpMult(rr, f, b);
VpAddSub(ff, res, rr, 1);
*dv = d;
*rv = ff;
return Qnil;
}
/* call-seq:
* remainder(value)
*
* Returns the remainder from dividing by the value.
*
* x.remainder(y) means x-y*(x/y).truncate
*/
static VALUE
BigDecimal_remainder(VALUE self, VALUE r) /* remainder */
{
VALUE f;
Real *d, *rv = 0;
f = BigDecimal_divremain(self, r, &d, &rv);
if (!NIL_P(f)) return f;
return VpCheckGetValue(rv);
}
/* call-seq:
* divmod(value)
*
* Divides by the specified value, and returns the quotient and modulus
* as BigDecimal numbers. The quotient is rounded towards negative infinity.
*
* For example:
*
* require 'bigdecimal'
*
* a = BigDecimal("42")
* b = BigDecimal("9")
*
* q, m = a.divmod(b)
*
* c = q * b + m
*
* a == c #=> true
*
* The quotient q is (a/b).floor, and the modulus is the amount that must be
* added to q * b to get a.
*/
static VALUE
BigDecimal_divmod(VALUE self, VALUE r)
{
ENTER(5);
Real *div = NULL, *mod = NULL;
if (BigDecimal_DoDivmod(self, r, &div, &mod)) {
SAVE(div); SAVE(mod);
return rb_assoc_new(VpCheckGetValue(div), VpCheckGetValue(mod));
}
return DoSomeOne(self,r,rb_intern("divmod"));
}
/*
* Do the same manner as Float#div when n is nil.
* Do the same manner as BigDecimal#quo when n is 0.
*/
static inline VALUE
BigDecimal_div2(VALUE self, VALUE b, VALUE n)
{
ENTER(5);
SIGNED_VALUE ix;
if (NIL_P(n)) { /* div in Float sense */
Real *div = NULL;
Real *mod;
if (BigDecimal_DoDivmod(self, b, &div, &mod)) {
return BigDecimal_to_i(VpCheckGetValue(div));
}
return DoSomeOne(self, b, rb_intern("div"));
}
/* div in BigDecimal sense */
ix = GetPrecisionInt(n);
if (ix == 0) {
return BigDecimal_div(self, b);
}
else {
Real *res = NULL;
Real *av = NULL, *bv = NULL, *cv = NULL;
size_t mx = ix + VpBaseFig()*2;
size_t b_prec = ix;
size_t pl = VpSetPrecLimit(0);
GUARD_OBJ(cv, VpCreateRbObject(mx + VpBaseFig(), "0", true));
GUARD_OBJ(av, GetVpValue(self, 1));
/* TODO: I want to refactor this precision control for a float value later
* by introducing an implicit conversion function instead of
* GetVpValueWithPrec. */
if (RB_FLOAT_TYPE_P(b) && b_prec > BIGDECIMAL_DOUBLE_FIGURES) {
b_prec = BIGDECIMAL_DOUBLE_FIGURES;
}
GUARD_OBJ(bv, GetVpValueWithPrec(b, b_prec, 1));
mx = av->Prec + bv->Prec + 2;
if (mx <= cv->MaxPrec) mx = cv->MaxPrec + 1;
GUARD_OBJ(res, VpCreateRbObject((mx * 2 + 2)*VpBaseFig(), "#0", true));
VpDivd(cv, res, av, bv);
VpSetPrecLimit(pl);
VpLeftRound(cv, VpGetRoundMode(), ix);
return VpCheckGetValue(cv);
}
}
/*
* Document-method: BigDecimal#div
*
* call-seq:
* div(value) -> integer
* div(value, digits) -> bigdecimal or integer
*
* Divide by the specified value.
*
* digits:: If specified and less than the number of significant digits of the
* result, the result is rounded to that number of digits, according
* to BigDecimal.mode.
*
* If digits is 0, the result is the same as for the / operator
* or #quo.
*
* If digits is not specified, the result is an integer,
* by analogy with Float#div; see also BigDecimal#divmod.
*
* See BigDecimal#/.
* See BigDecimal#quo.
*
* Examples:
*
* a = BigDecimal("4")
* b = BigDecimal("3")
*
* a.div(b, 3) # => 0.133e1
*
* a.div(b, 0) # => 0.1333333333333333333e1
* a / b # => 0.1333333333333333333e1
* a.quo(b) # => 0.1333333333333333333e1
*
* a.div(b) # => 1
*/
static VALUE
BigDecimal_div3(int argc, VALUE *argv, VALUE self)
{
VALUE b,n;
rb_scan_args(argc, argv, "11", &b, &n);
return BigDecimal_div2(self, b, n);
}
/*
* call-seq:
* add(value, ndigits) -> new_bigdecimal
*
* Returns the \BigDecimal sum of +self+ and +value+
* with a precision of +ndigits+ decimal digits.
*
* When +ndigits+ is less than the number of significant digits
* in the sum, the sum is rounded to that number of digits,
* according to the current rounding mode; see BigDecimal.mode.
*
* Examples:
*
* # Set the rounding mode.
* BigDecimal.mode(BigDecimal::ROUND_MODE, :half_up)
* b = BigDecimal('111111.111')
* b.add(1, 0) # => 0.111112111e6
* b.add(1, 3) # => 0.111e6
* b.add(1, 6) # => 0.111112e6
* b.add(1, 15) # => 0.111112111e6
* b.add(1.0, 15) # => 0.111112111e6
* b.add(Rational(1, 1), 15) # => 0.111112111e6
*
*/
static VALUE
BigDecimal_add2(VALUE self, VALUE b, VALUE n)
{
ENTER(2);
Real *cv;
SIGNED_VALUE mx = GetPrecisionInt(n);
if (mx == 0) return BigDecimal_add(self, b);
else {
size_t pl = VpSetPrecLimit(0);
VALUE c = BigDecimal_add(self, b);
VpSetPrecLimit(pl);
GUARD_OBJ(cv, GetVpValue(c, 1));
VpLeftRound(cv, VpGetRoundMode(), mx);
return VpCheckGetValue(cv);
}
}
/* call-seq:
* sub(value, digits) -> bigdecimal
*
* Subtract the specified value.
*
* e.g.
* c = a.sub(b,n)
*
* digits:: If specified and less than the number of significant digits of the
* result, the result is rounded to that number of digits, according
* to BigDecimal.mode.
*
*/
static VALUE
BigDecimal_sub2(VALUE self, VALUE b, VALUE n)
{
ENTER(2);
Real *cv;
SIGNED_VALUE mx = GetPrecisionInt(n);
if (mx == 0) return BigDecimal_sub(self, b);
else {
size_t pl = VpSetPrecLimit(0);
VALUE c = BigDecimal_sub(self, b);
VpSetPrecLimit(pl);
GUARD_OBJ(cv, GetVpValue(c, 1));
VpLeftRound(cv, VpGetRoundMode(), mx);
return VpCheckGetValue(cv);
}
}
/*
* call-seq:
* mult(other, ndigits) -> bigdecimal
*
* Returns the \BigDecimal product of +self+ and +value+
* with a precision of +ndigits+ decimal digits.
*
* When +ndigits+ is less than the number of significant digits
* in the sum, the sum is rounded to that number of digits,
* according to the current rounding mode; see BigDecimal.mode.
*
* Examples:
*
* # Set the rounding mode.
* BigDecimal.mode(BigDecimal::ROUND_MODE, :half_up)
* b = BigDecimal('555555.555')
* b.mult(3, 0) # => 0.1666666665e7
* b.mult(3, 3) # => 0.167e7
* b.mult(3, 6) # => 0.166667e7
* b.mult(3, 15) # => 0.1666666665e7
* b.mult(3.0, 0) # => 0.1666666665e7
* b.mult(Rational(3, 1), 0) # => 0.1666666665e7
* b.mult(Complex(3, 0), 0) # => (0.1666666665e7+0.0i)
*
*/
static VALUE
BigDecimal_mult2(VALUE self, VALUE b, VALUE n)
{
ENTER(2);
Real *cv;
SIGNED_VALUE mx = GetPrecisionInt(n);
if (mx == 0) return BigDecimal_mult(self, b);
else {
size_t pl = VpSetPrecLimit(0);
VALUE c = BigDecimal_mult(self, b);
VpSetPrecLimit(pl);
GUARD_OBJ(cv, GetVpValue(c, 1));
VpLeftRound(cv, VpGetRoundMode(), mx);
return VpCheckGetValue(cv);
}
}
/*
* call-seq:
* abs -> bigdecimal
*
* Returns the \BigDecimal absolute value of +self+:
*
* BigDecimal('5').abs # => 0.5e1
* BigDecimal('-3').abs # => 0.3e1
*
*/
static VALUE
BigDecimal_abs(VALUE self)
{
ENTER(5);
Real *c, *a;
size_t mx;
GUARD_OBJ(a, GetVpValue(self, 1));
mx = a->Prec *(VpBaseFig() + 1);
GUARD_OBJ(c, VpCreateRbObject(mx, "0", true));
VpAsgn(c, a, 1);
VpChangeSign(c, 1);
return VpCheckGetValue(c);
}
/* call-seq:
* sqrt(n)
*
* Returns the square root of the value.
*
* Result has at least n significant digits.
*/
static VALUE
BigDecimal_sqrt(VALUE self, VALUE nFig)
{
ENTER(5);
Real *c, *a;
size_t mx, n;
GUARD_OBJ(a, GetVpValue(self, 1));
mx = a->Prec * (VpBaseFig() + 1);
n = GetPrecisionInt(nFig) + VpDblFig() + BASE_FIG;
if (mx <= n) mx = n;
GUARD_OBJ(c, VpCreateRbObject(mx, "0", true));
VpSqrt(c, a);
return VpCheckGetValue(c);
}
/* Return the integer part of the number, as a BigDecimal.
*/
static VALUE
BigDecimal_fix(VALUE self)
{
ENTER(5);
Real *c, *a;
size_t mx;
GUARD_OBJ(a, GetVpValue(self, 1));
mx = a->Prec *(VpBaseFig() + 1);
GUARD_OBJ(c, VpCreateRbObject(mx, "0", true));
VpActiveRound(c, a, VP_ROUND_DOWN, 0); /* 0: round off */
return VpCheckGetValue(c);
}
/* call-seq:
* round(n, mode)
*
* Round to the nearest integer (by default), returning the result as a
* BigDecimal if n is specified, or as an Integer if it isn't.
*
* BigDecimal('3.14159').round #=> 3
* BigDecimal('8.7').round #=> 9
* BigDecimal('-9.9').round #=> -10
*
* BigDecimal('3.14159').round(2).class.name #=> "BigDecimal"
* BigDecimal('3.14159').round.class.name #=> "Integer"
*
* If n is specified and positive, the fractional part of the result has no
* more than that many digits.
*
* If n is specified and negative, at least that many digits to the left of the
* decimal point will be 0 in the result, and return value will be an Integer.
*
* BigDecimal('3.14159').round(3) #=> 3.142
* BigDecimal('13345.234').round(-2) #=> 13300
*
* The value of the optional mode argument can be used to determine how
* rounding is performed; see BigDecimal.mode.
*/
static VALUE
BigDecimal_round(int argc, VALUE *argv, VALUE self)
{
ENTER(5);
Real *c, *a;
int iLoc = 0;
VALUE vLoc;
VALUE vRound;
int round_to_int = 0;
size_t mx, pl;
unsigned short sw = VpGetRoundMode();
switch (rb_scan_args(argc, argv, "02", &vLoc, &vRound)) {
case 0:
iLoc = 0;
round_to_int = 1;
break;
case 1:
if (RB_TYPE_P(vLoc, T_HASH)) {
sw = check_rounding_mode_option(vLoc);
}
else {
iLoc = NUM2INT(vLoc);
if (iLoc < 1) round_to_int = 1;
}
break;
case 2:
iLoc = NUM2INT(vLoc);
if (RB_TYPE_P(vRound, T_HASH)) {
sw = check_rounding_mode_option(vRound);
}
else {
sw = check_rounding_mode(vRound);
}
break;
default:
break;
}
pl = VpSetPrecLimit(0);
GUARD_OBJ(a, GetVpValue(self, 1));
mx = a->Prec * (VpBaseFig() + 1);
GUARD_OBJ(c, VpCreateRbObject(mx, "0", true));
VpSetPrecLimit(pl);
VpActiveRound(c, a, sw, iLoc);
if (round_to_int) {
return BigDecimal_to_i(VpCheckGetValue(c));
}
return VpCheckGetValue(c);
}
/* call-seq:
* truncate(n)
*
* Truncate to the nearest integer (by default), returning the result as a
* BigDecimal.
*
* BigDecimal('3.14159').truncate #=> 3
* BigDecimal('8.7').truncate #=> 8
* BigDecimal('-9.9').truncate #=> -9
*
* If n is specified and positive, the fractional part of the result has no
* more than that many digits.
*
* If n is specified and negative, at least that many digits to the left of the
* decimal point will be 0 in the result.
*
* BigDecimal('3.14159').truncate(3) #=> 3.141
* BigDecimal('13345.234').truncate(-2) #=> 13300.0
*/
static VALUE
BigDecimal_truncate(int argc, VALUE *argv, VALUE self)
{
ENTER(5);
Real *c, *a;
int iLoc;
VALUE vLoc;
size_t mx, pl = VpSetPrecLimit(0);
if (rb_scan_args(argc, argv, "01", &vLoc) == 0) {
iLoc = 0;
}
else {
iLoc = NUM2INT(vLoc);
}
GUARD_OBJ(a, GetVpValue(self, 1));
mx = a->Prec * (VpBaseFig() + 1);
GUARD_OBJ(c, VpCreateRbObject(mx, "0", true));
VpSetPrecLimit(pl);
VpActiveRound(c, a, VP_ROUND_DOWN, iLoc); /* 0: truncate */
if (argc == 0) {
return BigDecimal_to_i(VpCheckGetValue(c));
}
return VpCheckGetValue(c);
}
/* Return the fractional part of the number, as a BigDecimal.
*/
static VALUE
BigDecimal_frac(VALUE self)
{
ENTER(5);
Real *c, *a;
size_t mx;
GUARD_OBJ(a, GetVpValue(self, 1));
mx = a->Prec * (VpBaseFig() + 1);
GUARD_OBJ(c, VpCreateRbObject(mx, "0", true));
VpFrac(c, a);
return VpCheckGetValue(c);
}
/* call-seq:
* floor(n)
*
* Return the largest integer less than or equal to the value, as a BigDecimal.
*
* BigDecimal('3.14159').floor #=> 3
* BigDecimal('-9.1').floor #=> -10
*
* If n is specified and positive, the fractional part of the result has no
* more than that many digits.
*
* If n is specified and negative, at least that
* many digits to the left of the decimal point will be 0 in the result.
*
* BigDecimal('3.14159').floor(3) #=> 3.141
* BigDecimal('13345.234').floor(-2) #=> 13300.0
*/
static VALUE
BigDecimal_floor(int argc, VALUE *argv, VALUE self)
{
ENTER(5);
Real *c, *a;
int iLoc;
VALUE vLoc;
size_t mx, pl = VpSetPrecLimit(0);
if (rb_scan_args(argc, argv, "01", &vLoc)==0) {
iLoc = 0;
}
else {
iLoc = NUM2INT(vLoc);
}
GUARD_OBJ(a, GetVpValue(self, 1));
mx = a->Prec * (VpBaseFig() + 1);
GUARD_OBJ(c, VpCreateRbObject(mx, "0", true));
VpSetPrecLimit(pl);
VpActiveRound(c, a, VP_ROUND_FLOOR, iLoc);
#ifdef BIGDECIMAL_DEBUG
VPrint(stderr, "floor: c=%\n", c);
#endif
if (argc == 0) {
return BigDecimal_to_i(VpCheckGetValue(c));
}
return VpCheckGetValue(c);
}
/* call-seq:
* ceil(n)
*
* Return the smallest integer greater than or equal to the value, as a BigDecimal.
*
* BigDecimal('3.14159').ceil #=> 4
* BigDecimal('-9.1').ceil #=> -9
*
* If n is specified and positive, the fractional part of the result has no
* more than that many digits.
*
* If n is specified and negative, at least that
* many digits to the left of the decimal point will be 0 in the result.
*
* BigDecimal('3.14159').ceil(3) #=> 3.142
* BigDecimal('13345.234').ceil(-2) #=> 13400.0
*/
static VALUE
BigDecimal_ceil(int argc, VALUE *argv, VALUE self)
{
ENTER(5);
Real *c, *a;
int iLoc;
VALUE vLoc;
size_t mx, pl = VpSetPrecLimit(0);
if (rb_scan_args(argc, argv, "01", &vLoc) == 0) {
iLoc = 0;
} else {
iLoc = NUM2INT(vLoc);
}
GUARD_OBJ(a, GetVpValue(self, 1));
mx = a->Prec * (VpBaseFig() + 1);
GUARD_OBJ(c, VpCreateRbObject(mx, "0", true));
VpSetPrecLimit(pl);
VpActiveRound(c, a, VP_ROUND_CEIL, iLoc);
if (argc == 0) {
return BigDecimal_to_i(VpCheckGetValue(c));
}
return VpCheckGetValue(c);
}
/* call-seq:
* to_s(s)
*
* Converts the value to a string.
*
* The default format looks like 0.xxxxEnn.
*
* The optional parameter s consists of either an integer; or an optional '+'
* or ' ', followed by an optional number, followed by an optional 'E' or 'F'.
*
* If there is a '+' at the start of s, positive values are returned with
* a leading '+'.
*
* A space at the start of s returns positive values with a leading space.
*
* If s contains a number, a space is inserted after each group of that many
* fractional digits.
*
* If s ends with an 'E', engineering notation (0.xxxxEnn) is used.
*
* If s ends with an 'F', conventional floating point notation is used.
*
* Examples:
*
* BigDecimal('-123.45678901234567890').to_s('5F')
* #=> '-123.45678 90123 45678 9'
*
* BigDecimal('123.45678901234567890').to_s('+8F')
* #=> '+123.45678901 23456789'
*
* BigDecimal('123.45678901234567890').to_s(' F')
* #=> ' 123.4567890123456789'
*/
static VALUE
BigDecimal_to_s(int argc, VALUE *argv, VALUE self)
{
ENTER(5);
int fmt = 0; /* 0: E format, 1: F format */
int fPlus = 0; /* 0: default, 1: set ' ' before digits, 2: set '+' before digits. */
Real *vp;
volatile VALUE str;
char *psz;
char ch;
size_t nc, mc = 0;
SIGNED_VALUE m;
VALUE f;
GUARD_OBJ(vp, GetVpValue(self, 1));
if (rb_scan_args(argc, argv, "01", &f) == 1) {
if (RB_TYPE_P(f, T_STRING)) {
psz = StringValueCStr(f);
if (*psz == ' ') {
fPlus = 1;
psz++;
}
else if (*psz == '+') {
fPlus = 2;
psz++;
}
while ((ch = *psz++) != 0) {
if (ISSPACE(ch)) {
continue;
}
if (!ISDIGIT(ch)) {
if (ch == 'F' || ch == 'f') {
fmt = 1; /* F format */
}
break;
}
mc = mc*10 + ch - '0';
}
}
else {
m = NUM2INT(f);
if (m <= 0) {
rb_raise(rb_eArgError, "argument must be positive");
}
mc = (size_t)m;
}
}
if (fmt) {
nc = VpNumOfChars(vp, "F");
}
else {
nc = VpNumOfChars(vp, "E");
}
if (mc > 0) {
nc += (nc + mc - 1) / mc + 1;
}
str = rb_usascii_str_new(0, nc);
psz = RSTRING_PTR(str);
if (fmt) {
VpToFString(vp, psz, mc, fPlus);
}
else {
VpToString (vp, psz, mc, fPlus);
}
rb_str_resize(str, strlen(psz));
return str;
}
/* Splits a BigDecimal number into four parts, returned as an array of values.
*
* The first value represents the sign of the BigDecimal, and is -1 or 1, or 0
* if the BigDecimal is Not a Number.
*
* The second value is a string representing the significant digits of the
* BigDecimal, with no leading zeros.
*
* The third value is the base used for arithmetic (currently always 10) as an
* Integer.
*
* The fourth value is an Integer exponent.
*
* If the BigDecimal can be represented as 0.xxxxxx*10**n, then xxxxxx is the
* string of significant digits with no leading zeros, and n is the exponent.
*
* From these values, you can translate a BigDecimal to a float as follows:
*
* sign, significant_digits, base, exponent = a.split
* f = sign * "0.#{significant_digits}".to_f * (base ** exponent)
*
* (Note that the to_f method is provided as a more convenient way to translate
* a BigDecimal to a Float.)
*/
static VALUE
BigDecimal_split(VALUE self)
{
ENTER(5);
Real *vp;
VALUE obj,str;
ssize_t e, s;
char *psz1;
GUARD_OBJ(vp, GetVpValue(self, 1));
str = rb_str_new(0, VpNumOfChars(vp, "E"));
psz1 = RSTRING_PTR(str);
VpSzMantissa(vp, psz1);
s = 1;
if(psz1[0] == '-') {
size_t len = strlen(psz1 + 1);
memmove(psz1, psz1 + 1, len);
psz1[len] = '\0';
s = -1;
}
if (psz1[0] == 'N') s = 0; /* NaN */
e = VpExponent10(vp);
obj = rb_ary_new2(4);
rb_ary_push(obj, INT2FIX(s));
rb_ary_push(obj, str);
rb_str_resize(str, strlen(psz1));
rb_ary_push(obj, INT2FIX(10));
rb_ary_push(obj, SSIZET2NUM(e));
return obj;
}
/* Returns the exponent of the BigDecimal number, as an Integer.
*
* If the number can be represented as 0.xxxxxx*10**n where xxxxxx is a string
* of digits with no leading zeros, then n is the exponent.
*/
static VALUE
BigDecimal_exponent(VALUE self)
{
ssize_t e = VpExponent10(GetVpValue(self, 1));
return SSIZET2NUM(e);
}
/* Returns a string representation of self.
*
* BigDecimal("1234.5678").inspect
* #=> "0.12345678e4"
*/
static VALUE
BigDecimal_inspect(VALUE self)
{
ENTER(5);
Real *vp;
volatile VALUE str;
size_t nc;
GUARD_OBJ(vp, GetVpValue(self, 1));
nc = VpNumOfChars(vp, "E");
str = rb_str_new(0, nc);
VpToString(vp, RSTRING_PTR(str), 0, 0);
rb_str_resize(str, strlen(RSTRING_PTR(str)));
return str;
}
static VALUE BigMath_s_exp(VALUE, VALUE, VALUE);
static VALUE BigMath_s_log(VALUE, VALUE, VALUE);
#define BigMath_exp(x, n) BigMath_s_exp(rb_mBigMath, (x), (n))
#define BigMath_log(x, n) BigMath_s_log(rb_mBigMath, (x), (n))
inline static int
is_integer(VALUE x)
{
return (RB_TYPE_P(x, T_FIXNUM) || RB_TYPE_P(x, T_BIGNUM));
}
inline static int
is_negative(VALUE x)
{
if (FIXNUM_P(x)) {
return FIX2LONG(x) < 0;
}
else if (RB_TYPE_P(x, T_BIGNUM)) {
return FIX2INT(rb_big_cmp(x, INT2FIX(0))) < 0;
}
else if (RB_TYPE_P(x, T_FLOAT)) {
return RFLOAT_VALUE(x) < 0.0;
}
return RTEST(rb_funcall(x, '<', 1, INT2FIX(0)));
}
#define is_positive(x) (!is_negative(x))
inline static int
is_zero(VALUE x)
{
VALUE num;
switch (TYPE(x)) {
case T_FIXNUM:
return FIX2LONG(x) == 0;
case T_BIGNUM:
return Qfalse;
case T_RATIONAL:
num = rb_rational_num(x);
return FIXNUM_P(num) && FIX2LONG(num) == 0;
default:
break;
}
return RTEST(rb_funcall(x, id_eq, 1, INT2FIX(0)));
}
inline static int
is_one(VALUE x)
{
VALUE num, den;
switch (TYPE(x)) {
case T_FIXNUM:
return FIX2LONG(x) == 1;
case T_BIGNUM:
return Qfalse;
case T_RATIONAL:
num = rb_rational_num(x);
den = rb_rational_den(x);
return FIXNUM_P(den) && FIX2LONG(den) == 1 &&
FIXNUM_P(num) && FIX2LONG(num) == 1;
default:
break;
}
return RTEST(rb_funcall(x, id_eq, 1, INT2FIX(1)));
}
inline static int
is_even(VALUE x)
{
switch (TYPE(x)) {
case T_FIXNUM:
return (FIX2LONG(x) % 2) == 0;
case T_BIGNUM:
{
unsigned long l;
rb_big_pack(x, &l, 1);
return l % 2 == 0;
}
default:
break;
}
return 0;
}
static VALUE
bigdecimal_power_by_bigdecimal(Real const* x, Real const* exp, ssize_t const n)
{
VALUE log_x, multiplied, y;
volatile VALUE obj = exp->obj;
if (VpIsZero(exp)) {
return VpCheckGetValue(VpCreateRbObject(n, "1", true));
}
log_x = BigMath_log(x->obj, SSIZET2NUM(n+1));
multiplied = BigDecimal_mult2(exp->obj, log_x, SSIZET2NUM(n+1));
y = BigMath_exp(multiplied, SSIZET2NUM(n));
RB_GC_GUARD(obj);
return y;
}
/* call-seq:
* power(n)
* power(n, prec)
*
* Returns the value raised to the power of n.
*
* Note that n must be an Integer.
*
* Also available as the operator **.
*/
static VALUE
BigDecimal_power(int argc, VALUE*argv, VALUE self)
{
ENTER(5);
VALUE vexp, prec;
Real* exp = NULL;
Real *x, *y;
ssize_t mp, ma, n;
SIGNED_VALUE int_exp;
double d;
rb_scan_args(argc, argv, "11", &vexp, &prec);
GUARD_OBJ(x, GetVpValue(self, 1));
n = NIL_P(prec) ? (ssize_t)(x->Prec*VpBaseFig()) : NUM2SSIZET(prec);
if (VpIsNaN(x)) {
y = VpCreateRbObject(n, "0", true);
RB_GC_GUARD(y->obj);
VpSetNaN(y);
return VpCheckGetValue(y);
}
retry:
switch (TYPE(vexp)) {
case T_FIXNUM:
break;
case T_BIGNUM:
break;
case T_FLOAT:
d = RFLOAT_VALUE(vexp);
if (d == round(d)) {
if (FIXABLE(d)) {
vexp = LONG2FIX((long)d);
}
else {
vexp = rb_dbl2big(d);
}
goto retry;
}
if (NIL_P(prec)) {
n += BIGDECIMAL_DOUBLE_FIGURES;
}
exp = GetVpValueWithPrec(vexp, 0, 1);
break;
case T_RATIONAL:
if (is_zero(rb_rational_num(vexp))) {
if (is_positive(vexp)) {
vexp = INT2FIX(0);
goto retry;
}
}
else if (is_one(rb_rational_den(vexp))) {
vexp = rb_rational_num(vexp);
goto retry;
}
exp = GetVpValueWithPrec(vexp, n, 1);
if (NIL_P(prec)) {
n += n;
}
break;
case T_DATA:
if (is_kind_of_BigDecimal(vexp)) {
VALUE zero = INT2FIX(0);
VALUE rounded = BigDecimal_round(1, &zero, vexp);
if (RTEST(BigDecimal_eq(vexp, rounded))) {
vexp = BigDecimal_to_i(vexp);
goto retry;
}
if (NIL_P(prec)) {
GUARD_OBJ(y, GetVpValue(vexp, 1));
n += y->Prec*VpBaseFig();
}
exp = DATA_PTR(vexp);
break;
}
/* fall through */
default:
rb_raise(rb_eTypeError,
"wrong argument type %"PRIsVALUE" (expected scalar Numeric)",
RB_OBJ_CLASSNAME(vexp));
}
if (VpIsZero(x)) {
if (is_negative(vexp)) {
y = VpCreateRbObject(n, "#0", true);
RB_GC_GUARD(y->obj);
if (BIGDECIMAL_NEGATIVE_P(x)) {
if (is_integer(vexp)) {
if (is_even(vexp)) {
/* (-0) ** (-even_integer) -> Infinity */
VpSetPosInf(y);
}
else {
/* (-0) ** (-odd_integer) -> -Infinity */
VpSetNegInf(y);
}
}
else {
/* (-0) ** (-non_integer) -> Infinity */
VpSetPosInf(y);
}
}
else {
/* (+0) ** (-num) -> Infinity */
VpSetPosInf(y);
}
return VpCheckGetValue(y);
}
else if (is_zero(vexp)) {
return VpCheckGetValue(VpCreateRbObject(n, "1", true));
}
else {
return VpCheckGetValue(VpCreateRbObject(n, "0", true));
}
}
if (is_zero(vexp)) {
return VpCheckGetValue(VpCreateRbObject(n, "1", true));
}
else if (is_one(vexp)) {
return self;
}
if (VpIsInf(x)) {
if (is_negative(vexp)) {
if (BIGDECIMAL_NEGATIVE_P(x)) {
if (is_integer(vexp)) {
if (is_even(vexp)) {
/* (-Infinity) ** (-even_integer) -> +0 */
return VpCheckGetValue(VpCreateRbObject(n, "0", true));
}
else {
/* (-Infinity) ** (-odd_integer) -> -0 */
return VpCheckGetValue(VpCreateRbObject(n, "-0", true));
}
}
else {
/* (-Infinity) ** (-non_integer) -> -0 */
return VpCheckGetValue(VpCreateRbObject(n, "-0", true));
}
}
else {
return VpCheckGetValue(VpCreateRbObject(n, "0", true));
}
}
else {
y = VpCreateRbObject(n, "0", true);
if (BIGDECIMAL_NEGATIVE_P(x)) {
if (is_integer(vexp)) {
if (is_even(vexp)) {
VpSetPosInf(y);
}
else {
VpSetNegInf(y);
}
}
else {
/* TODO: support complex */
rb_raise(rb_eMathDomainError,
"a non-integral exponent for a negative base");
}
}
else {
VpSetPosInf(y);
}
return VpCheckGetValue(y);
}
}
if (exp != NULL) {
return bigdecimal_power_by_bigdecimal(x, exp, n);
}
else if (RB_TYPE_P(vexp, T_BIGNUM)) {
VALUE abs_value = BigDecimal_abs(self);
if (is_one(abs_value)) {
return VpCheckGetValue(VpCreateRbObject(n, "1", true));
}
else if (RTEST(rb_funcall(abs_value, '<', 1, INT2FIX(1)))) {
if (is_negative(vexp)) {
y = VpCreateRbObject(n, "0", true);
if (is_even(vexp)) {
VpSetInf(y, VpGetSign(x));
}
else {
VpSetInf(y, -VpGetSign(x));
}
return VpCheckGetValue(y);
}
else if (BIGDECIMAL_NEGATIVE_P(x) && is_even(vexp)) {
return VpCheckGetValue(VpCreateRbObject(n, "-0", true));
}
else {
return VpCheckGetValue(VpCreateRbObject(n, "0", true));
}
}
else {
if (is_positive(vexp)) {
y = VpCreateRbObject(n, "0", true);
if (is_even(vexp)) {
VpSetInf(y, VpGetSign(x));
}
else {
VpSetInf(y, -VpGetSign(x));
}
return VpCheckGetValue(y);
}
else if (BIGDECIMAL_NEGATIVE_P(x) && is_even(vexp)) {
return VpCheckGetValue(VpCreateRbObject(n, "-0", true));
}
else {
return VpCheckGetValue(VpCreateRbObject(n, "0", true));
}
}
}
int_exp = FIX2LONG(vexp);
ma = int_exp;
if (ma < 0) ma = -ma;
if (ma == 0) ma = 1;
if (VpIsDef(x)) {
mp = x->Prec * (VpBaseFig() + 1);
GUARD_OBJ(y, VpCreateRbObject(mp * (ma + 1), "0", true));
}
else {
GUARD_OBJ(y, VpCreateRbObject(1, "0", true));
}
VpPowerByInt(y, x, int_exp);
if (!NIL_P(prec) && VpIsDef(y)) {
VpMidRound(y, VpGetRoundMode(), n);
}
return VpCheckGetValue(y);
}
/* call-seq:
* self ** other -> bigdecimal
*
* Returns the \BigDecimal value of +self+ raised to power +other+:
*
* b = BigDecimal('3.14')
* b ** 2 # => 0.98596e1
* b ** 2.0 # => 0.98596e1
* b ** Rational(2, 1) # => 0.98596e1
*
* Related: BigDecimal#power.
*
*/
static VALUE
BigDecimal_power_op(VALUE self, VALUE exp)
{
return BigDecimal_power(1, &exp, self);
}
/* :nodoc:
*
* private method for dup and clone the provided BigDecimal +other+
*/
static VALUE
BigDecimal_initialize_copy(VALUE self, VALUE other)
{
Real *pv = rb_check_typeddata(self, &BigDecimal_data_type);
Real *x = rb_check_typeddata(other, &BigDecimal_data_type);
if (self != other) {
DATA_PTR(self) = VpCopy(pv, x);
}
return self;
}
static VALUE
BigDecimal_clone(VALUE self)
{
return self;
}
#ifdef HAVE_RB_OPTS_EXCEPTION_P
int rb_opts_exception_p(VALUE opts, int default_value);
#define opts_exception_p(opts) rb_opts_exception_p((opts), 1)
#else
static int
opts_exception_p(VALUE opts)
{
static ID kwds[1];
VALUE exception;
if (!kwds[0]) {
kwds[0] = rb_intern_const("exception");
}
if (!rb_get_kwargs(opts, kwds, 0, 1, &exception)) return 1;
switch (exception) {
case Qtrue: case Qfalse:
break;
default:
rb_raise(rb_eArgError, "true or false is expected as exception: %+"PRIsVALUE,
exception);
}
return exception != Qfalse;
}
#endif
static VALUE
check_exception(VALUE bd)
{
assert(is_kind_of_BigDecimal(bd));
Real *vp;
TypedData_Get_Struct(bd, Real, &BigDecimal_data_type, vp);
VpCheckGetValue(vp); /* VpCheckGetValue performs exception check */
return bd;
}
static VALUE
rb_uint64_convert_to_BigDecimal(uint64_t uval, RB_UNUSED_VAR(size_t digs), int raise_exception)
{
VALUE obj = TypedData_Wrap_Struct(rb_cBigDecimal, &BigDecimal_data_type, 0);
Real *vp;
if (uval == 0) {
vp = VpAllocReal(1);
vp->MaxPrec = 1;
vp->Prec = 1;
vp->exponent = 1;
VpSetZero(vp, 1);
vp->frac[0] = 0;
}
else if (uval < BASE) {
vp = VpAllocReal(1);
vp->MaxPrec = 1;
vp->Prec = 1;
vp->exponent = 1;
VpSetSign(vp, 1);
vp->frac[0] = (DECDIG)uval;
}
else {
DECDIG buf[BIGDECIMAL_INT64_MAX_LENGTH] = {0,};
DECDIG r = uval % BASE;
size_t len = 0, ntz = 0;
if (r == 0) {
// Count and skip trailing zeros
for (; r == 0 && uval > 0; ++ntz) {
uval /= BASE;
r = uval % BASE;
}
}
for (; uval > 0; ++len) {
// Store digits
buf[BIGDECIMAL_INT64_MAX_LENGTH - len - 1] = r;
uval /= BASE;
r = uval % BASE;
}
const size_t exp = len + ntz;
vp = VpAllocReal(len);
vp->MaxPrec = len;
vp->Prec = len;
vp->exponent = exp;
VpSetSign(vp, 1);
MEMCPY(vp->frac, buf + BIGDECIMAL_INT64_MAX_LENGTH - len, DECDIG, len);
}
return BigDecimal_wrap_struct(obj, vp);
}
static VALUE
rb_int64_convert_to_BigDecimal(int64_t ival, size_t digs, int raise_exception)
{
const uint64_t uval = (ival < 0) ? (((uint64_t)-(ival+1))+1) : (uint64_t)ival;
VALUE bd = rb_uint64_convert_to_BigDecimal(uval, digs, raise_exception);
if (ival < 0) {
Real *vp;
TypedData_Get_Struct(bd, Real, &BigDecimal_data_type, vp);
VpSetSign(vp, -1);
}
return bd;
}
static VALUE
rb_big_convert_to_BigDecimal(VALUE val, RB_UNUSED_VAR(size_t digs), int raise_exception)
{
assert(RB_TYPE_P(val, T_BIGNUM));
int leading_zeros;
size_t size = rb_absint_size(val, &leading_zeros);
int sign = FIX2INT(rb_big_cmp(val, INT2FIX(0)));
if (sign < 0 && leading_zeros == 0) {
size += 1;
}
if (size <= sizeof(long)) {
if (sign < 0) {
return rb_int64_convert_to_BigDecimal(NUM2LONG(val), digs, raise_exception);
}
else {
return rb_uint64_convert_to_BigDecimal(NUM2ULONG(val), digs, raise_exception);
}
}
#if defined(SIZEOF_LONG_LONG) && SIZEOF_LONG < SIZEOF_LONG_LONG
else if (size <= sizeof(LONG_LONG)) {
if (sign < 0) {
return rb_int64_convert_to_BigDecimal(NUM2LL(val), digs, raise_exception);
}
else {
return rb_uint64_convert_to_BigDecimal(NUM2ULL(val), digs, raise_exception);
}
}
#endif
else {
VALUE str = rb_big2str(val, 10);
Real *vp = VpCreateRbObject(RSTRING_LEN(str) + BASE_FIG + 1,
RSTRING_PTR(str), true);
RB_GC_GUARD(str);
return check_exception(vp->obj);
}
}
static VALUE
rb_inum_convert_to_BigDecimal(VALUE val, RB_UNUSED_VAR(size_t digs), int raise_exception)
{
assert(RB_INTEGER_TYPE_P(val));
if (FIXNUM_P(val)) {
return rb_int64_convert_to_BigDecimal(FIX2LONG(val), digs, raise_exception);
}
else {
return rb_big_convert_to_BigDecimal(val, digs, raise_exception);
}
}
static VALUE
rb_float_convert_to_BigDecimal(VALUE val, size_t digs, int raise_exception)
{
assert(RB_FLOAT_TYPE_P(val));
double d = RFLOAT_VALUE(val);
if (isnan(d)) {
VALUE obj = BigDecimal_nan();
return check_exception(obj);
}
else if (isinf(d)) {
VALUE obj;
if (d > 0) {
obj = BigDecimal_positive_infinity();
}
else {
obj = BigDecimal_negative_infinity();
}
return check_exception(obj);
}
else if (d == 0.0) {
if (1/d < 0.0) {
return BigDecimal_negative_zero();
}
else {
return BigDecimal_positive_zero();
}
}
if (digs == SIZE_MAX) {
if (!raise_exception)
return Qnil;
rb_raise(rb_eArgError,
"can't omit precision for a %"PRIsVALUE".",
CLASS_OF(val));
}
else if (digs > BIGDECIMAL_DOUBLE_FIGURES) {
if (!raise_exception)
return Qnil;
rb_raise(rb_eArgError, "precision too large.");
}
/* Use the same logic in flo_to_s to convert a float to a decimal string */
char buf[BIGDECIMAL_DOUBLE_FIGURES + BASE_FIG + 2 + 1]; /* sizeof(buf) == 28 in the typical case */
int decpt, negative_p;
char *e;
const int mode = digs == 0 ? 0 : 2;
char *p = BigDecimal_dtoa(d, mode, (int)digs, &decpt, &negative_p, &e);
int len10 = (int)(e - p);
if (len10 > BIGDECIMAL_DOUBLE_FIGURES) {
/* TODO: Presumably, rounding should be done here. */
len10 = BIGDECIMAL_DOUBLE_FIGURES;
}
memcpy(buf, p, len10);
xfree(p);
VALUE inum;
size_t RB_UNUSED_VAR(prec) = 0;
SIGNED_VALUE exp = 0;
if (decpt > 0) {
if (decpt < len10) {
/*
* len10 |---------------|
* : |-------| frac_len10 = len10 - decpt
* decpt |-------| |--| ntz10 = BASE_FIG - frac_len10 % BASE_FIG
* : : :
* 00 dd dddd.dddd dd 00
* prec |-----.----.----.-----| prec = exp + roomof(frac_len, BASE_FIG)
* exp |-----.----| exp = roomof(decpt, BASE_FIG)
*/
const size_t frac_len10 = len10 - decpt;
const size_t ntz10 = BASE_FIG - frac_len10 % BASE_FIG;
memset(buf + len10, '0', ntz10);
buf[len10 + ntz10] = '\0';
inum = rb_cstr_to_inum(buf, 10, false);
exp = roomof(decpt, BASE_FIG);
prec = exp + roomof(frac_len10, BASE_FIG);
}
else {
/*
* decpt |-----------------------|
* len10 |----------| :
* : |------------| exp10
* : : :
* 00 dd dddd dd 00 0000 0000.0
* : : : :
* : |--| ntz10 = exp10 % BASE_FIG
* prec |-----.----.-----| :
* : |----.----| exp10 / BASE_FIG
* exp |-----.----.-----.----.----|
*/
const size_t exp10 = decpt - len10;
const size_t ntz10 = exp10 % BASE_FIG;
memset(buf + len10, '0', ntz10);
buf[len10 + ntz10] = '\0';
inum = rb_cstr_to_inum(buf, 10, false);
prec = roomof(len10 + ntz10, BASE_FIG);
exp = prec + exp10 / BASE_FIG;
}
}
else if (decpt == 0) {
/*
* len10 |------------|
* : :
* 0.dddd dddd dd 00
* : : :
* : |--| ntz10 = prec * BASE_FIG - len10
* prec |----.----.-----| roomof(len10, BASE_FIG)
*/
prec = roomof(len10, BASE_FIG);
const size_t ntz10 = prec * BASE_FIG - len10;
memset(buf + len10, '0', ntz10);
buf[len10 + ntz10] = '\0';
inum = rb_cstr_to_inum(buf, 10, false);
}
else {
/*
* len10 |---------------|
* : :
* decpt |-------| |--| ntz10 = prec * BASE_FIG - nlz10 - len10
* : : :
* 0.0000 00 dd dddd dddd dd 00
* : : :
* nlz10 |--| : decpt % BASE_FIG
* prec |-----.----.----.-----| roomof(decpt + len10, BASE_FIG) - exp
* exp |----| decpt / BASE_FIG
*/
decpt = -decpt;
const size_t nlz10 = decpt % BASE_FIG;
exp = decpt / BASE_FIG;
prec = roomof(decpt + len10, BASE_FIG) - exp;
const size_t ntz10 = prec * BASE_FIG - nlz10 - len10;
if (nlz10 > 0) {
memmove(buf + nlz10, buf, len10);
memset(buf, '0', nlz10);
}
memset(buf + nlz10 + len10, '0', ntz10);
buf[nlz10 + len10 + ntz10] = '\0';
inum = rb_cstr_to_inum(buf, 10, false);
exp = -exp;
}
VALUE bd = rb_inum_convert_to_BigDecimal(inum, SIZE_MAX, raise_exception);
Real *vp;
TypedData_Get_Struct(bd, Real, &BigDecimal_data_type, vp);
assert(vp->Prec == prec);
vp->exponent = exp;
if (negative_p) VpSetSign(vp, -1);
return bd;
}
static VALUE
rb_rational_convert_to_BigDecimal(VALUE val, size_t digs, int raise_exception)
{
assert(RB_TYPE_P(val, T_RATIONAL));
if (digs == SIZE_MAX) {
if (!raise_exception)
return Qnil;
rb_raise(rb_eArgError,
"can't omit precision for a %"PRIsVALUE".",
CLASS_OF(val));
}
VALUE num = rb_inum_convert_to_BigDecimal(rb_rational_num(val), 0, raise_exception);
VALUE d = BigDecimal_div2(num, rb_rational_den(val), SIZET2NUM(digs));
return d;
}
static VALUE
rb_cstr_convert_to_BigDecimal(const char *c_str, size_t digs, int raise_exception)
{
if (digs == SIZE_MAX)
digs = 0;
Real *vp = VpCreateRbObject(digs, c_str, raise_exception);
if (!vp)
return Qnil;
return VpCheckGetValue(vp);
}
static inline VALUE
rb_str_convert_to_BigDecimal(VALUE val, size_t digs, int raise_exception)
{
const char *c_str = StringValueCStr(val);
return rb_cstr_convert_to_BigDecimal(c_str, digs, raise_exception);
}
static VALUE
rb_convert_to_BigDecimal(VALUE val, size_t digs, int raise_exception)
{
switch (val) {
case Qnil:
case Qtrue:
case Qfalse:
if (raise_exception) {
const char *cname = NIL_P(val) ? "nil" :
val == Qtrue ? "true" :
val == Qfalse ? "false" :
NULL;
rb_raise(rb_eTypeError,
"can't convert %s into BigDecimal", cname);
}
return Qnil;
default:
break;
}
if (is_kind_of_BigDecimal(val)) {
if (digs == SIZE_MAX)
return check_exception(val);
Real *vp;
TypedData_Get_Struct(val, Real, &BigDecimal_data_type, vp);
VALUE copy = TypedData_Wrap_Struct(rb_cBigDecimal, &BigDecimal_data_type, 0);
vp = VpCopy(NULL, vp);
/* TODO: rounding */
BigDecimal_wrap_struct(copy, vp);
return VpCheckGetValue(vp);
}
else if (RB_INTEGER_TYPE_P(val)) {
return rb_inum_convert_to_BigDecimal(val, digs, raise_exception);
}
else if (RB_FLOAT_TYPE_P(val)) {
return rb_float_convert_to_BigDecimal(val, digs, raise_exception);
}
else if (RB_TYPE_P(val, T_RATIONAL)) {
return rb_rational_convert_to_BigDecimal(val, digs, raise_exception);
}
else if (RB_TYPE_P(val, T_COMPLEX)) {
VALUE im = rb_complex_imag(val);
if (!is_zero(im)) {
/* TODO: handle raise_exception */
rb_raise(rb_eArgError,
"Unable to make a BigDecimal from non-zero imaginary number");
}
return rb_convert_to_BigDecimal(rb_complex_real(val), digs, raise_exception);
}
else if (RB_TYPE_P(val, T_STRING)) {
return rb_str_convert_to_BigDecimal(val, digs, raise_exception);
}
/* TODO: chheck to_d */
/* TODO: chheck to_int */
VALUE str = rb_check_convert_type(val, T_STRING, "String", "to_str");
if (!RB_TYPE_P(str, T_STRING)) {
if (raise_exception) {
rb_raise(rb_eTypeError,
"can't convert %"PRIsVALUE" into BigDecimal", rb_obj_class(val));
}
return Qnil;
}
return rb_str_convert_to_BigDecimal(str, digs, raise_exception);
}
/* call-seq:
* BigDecimal(value, exception: true) -> bigdecimal
* BigDecimal(value, ndigits, exception: true) -> bigdecimal
*
* Returns the \BigDecimal converted from +value+
* with a precision of +ndigits+ decimal digits.
*
* When +ndigits+ is less than the number of significant digits
* in the value, the result is rounded to that number of digits,
* according to the current rounding mode; see BigDecimal.mode.
*
* Returns +value+ converted to a \BigDecimal, depending on the type of +value+:
*
* - Integer, Float, Rational, Complex, or BigDecimal: converted directly:
*
* # Integer, Complex, or BigDecimal value does not require ndigits; ignored if given.
* BigDecimal(2) # => 0.2e1
* BigDecimal(Complex(2, 0)) # => 0.2e1
* BigDecimal(BigDecimal(2)) # => 0.2e1
* # Float or Rational value requires ndigits.
* BigDecimal(2.0, 0) # => 0.2e1
* BigDecimal(Rational(2, 1), 0) # => 0.2e1
*
* - String: converted by parsing if it contains an integer or floating-point literal;
* leading and trailing whitespace is ignored:
*
* # String does not require ndigits; ignored if given.
* BigDecimal('2') # => 0.2e1
* BigDecimal('2.0') # => 0.2e1
* BigDecimal('0.2e1') # => 0.2e1
* BigDecimal(' 2.0 ') # => 0.2e1
*
* - Other type that responds to method <tt>:to_str</tt>:
* first converted to a string, then converted to a \BigDecimal, as above.
*
* - Other type:
*
* - Raises an exception if keyword argument +exception+ is +true+.
* - Returns +nil+ if keyword argument +exception+ is +true+.
*
* Raises an exception if +value+ evaluates to a Float
* and +digits+ is larger than Float::DIG + 1.
*
*/
static VALUE
f_BigDecimal(int argc, VALUE *argv, VALUE self)
{
VALUE val, digs_v, opts = Qnil;
argc = rb_scan_args(argc, argv, "11:", &val, &digs_v, &opts);
int exception = opts_exception_p(opts);
size_t digs = SIZE_MAX; /* this means digs is omitted */
if (argc > 1) {
digs_v = rb_to_int(digs_v);
if (FIXNUM_P(digs_v)) {
long n = FIX2LONG(digs_v);
if (n < 0)
goto negative_digs;
digs = (size_t)n;
}
else {
if (RBIGNUM_NEGATIVE_P(digs_v)) {
negative_digs:
if (!exception)
return Qnil;
rb_raise(rb_eArgError, "negative precision");
}
digs = NUM2SIZET(digs_v);
}
}
return rb_convert_to_BigDecimal(val, digs, exception);
}
static VALUE
BigDecimal_s_interpret_loosely(VALUE klass, VALUE str)
{
char const *c_str = StringValueCStr(str);
Real *vp = VpNewRbClass(0, c_str, klass, false, true);
if (!vp)
return Qnil;
else
return VpCheckGetValue(vp);
}
/* call-seq:
* BigDecimal.limit(digits)
*
* Limit the number of significant digits in newly created BigDecimal
* numbers to the specified value. Rounding is performed as necessary,
* as specified by BigDecimal.mode.
*
* A limit of 0, the default, means no upper limit.
*
* The limit specified by this method takes less priority over any limit
* specified to instance methods such as ceil, floor, truncate, or round.
*/
static VALUE
BigDecimal_limit(int argc, VALUE *argv, VALUE self)
{
VALUE nFig;
VALUE nCur = SIZET2NUM(VpGetPrecLimit());
if (rb_scan_args(argc, argv, "01", &nFig) == 1) {
int nf;
if (NIL_P(nFig)) return nCur;
nf = NUM2INT(nFig);
if (nf < 0) {
rb_raise(rb_eArgError, "argument must be positive");
}
VpSetPrecLimit(nf);
}
return nCur;
}
/* Returns the sign of the value.
*
* Returns a positive value if > 0, a negative value if < 0, and a
* zero if == 0.
*
* The specific value returned indicates the type and sign of the BigDecimal,
* as follows:
*
* BigDecimal::SIGN_NaN:: value is Not a Number
* BigDecimal::SIGN_POSITIVE_ZERO:: value is +0
* BigDecimal::SIGN_NEGATIVE_ZERO:: value is -0
* BigDecimal::SIGN_POSITIVE_INFINITE:: value is +Infinity
* BigDecimal::SIGN_NEGATIVE_INFINITE:: value is -Infinity
* BigDecimal::SIGN_POSITIVE_FINITE:: value is positive
* BigDecimal::SIGN_NEGATIVE_FINITE:: value is negative
*/
static VALUE
BigDecimal_sign(VALUE self)
{ /* sign */
int s = GetVpValue(self, 1)->sign;
return INT2FIX(s);
}
/*
* call-seq: BigDecimal.save_exception_mode { ... }
*
* Execute the provided block, but preserve the exception mode
*
* BigDecimal.save_exception_mode do
* BigDecimal.mode(BigDecimal::EXCEPTION_OVERFLOW, false)
* BigDecimal.mode(BigDecimal::EXCEPTION_NaN, false)
*
* BigDecimal(BigDecimal('Infinity'))
* BigDecimal(BigDecimal('-Infinity'))
* BigDecimal(BigDecimal('NaN'))
* end
*
* For use with the BigDecimal::EXCEPTION_*
*
* See BigDecimal.mode
*/
static VALUE
BigDecimal_save_exception_mode(VALUE self)
{
unsigned short const exception_mode = VpGetException();
int state;
VALUE ret = rb_protect(rb_yield, Qnil, &state);
VpSetException(exception_mode);
if (state) rb_jump_tag(state);
return ret;
}
/*
* call-seq: BigDecimal.save_rounding_mode { ... }
*
* Execute the provided block, but preserve the rounding mode
*
* BigDecimal.save_rounding_mode do
* BigDecimal.mode(BigDecimal::ROUND_MODE, :up)
* puts BigDecimal.mode(BigDecimal::ROUND_MODE)
* end
*
* For use with the BigDecimal::ROUND_*
*
* See BigDecimal.mode
*/
static VALUE
BigDecimal_save_rounding_mode(VALUE self)
{
unsigned short const round_mode = VpGetRoundMode();
int state;
VALUE ret = rb_protect(rb_yield, Qnil, &state);
VpSetRoundMode(round_mode);
if (state) rb_jump_tag(state);
return ret;
}
/*
* call-seq: BigDecimal.save_limit { ... }
*
* Execute the provided block, but preserve the precision limit
*
* BigDecimal.limit(100)
* puts BigDecimal.limit
* BigDecimal.save_limit do
* BigDecimal.limit(200)
* puts BigDecimal.limit
* end
* puts BigDecimal.limit
*
*/
static VALUE
BigDecimal_save_limit(VALUE self)
{
size_t const limit = VpGetPrecLimit();
int state;
VALUE ret = rb_protect(rb_yield, Qnil, &state);
VpSetPrecLimit(limit);
if (state) rb_jump_tag(state);
return ret;
}
/* call-seq:
* BigMath.exp(decimal, numeric) -> BigDecimal
*
* Computes the value of e (the base of natural logarithms) raised to the
* power of +decimal+, to the specified number of digits of precision.
*
* If +decimal+ is infinity, returns Infinity.
*
* If +decimal+ is NaN, returns NaN.
*/
static VALUE
BigMath_s_exp(VALUE klass, VALUE x, VALUE vprec)
{
ssize_t prec, n, i;
Real* vx = NULL;
VALUE one, d, y;
int negative = 0;
int infinite = 0;
int nan = 0;
double flo;
prec = NUM2SSIZET(vprec);
if (prec <= 0) {
rb_raise(rb_eArgError, "Zero or negative precision for exp");
}
/* TODO: the following switch statement is almost same as one in the
* BigDecimalCmp function. */
switch (TYPE(x)) {
case T_DATA:
if (!is_kind_of_BigDecimal(x)) break;
vx = DATA_PTR(x);
negative = BIGDECIMAL_NEGATIVE_P(vx);
infinite = VpIsPosInf(vx) || VpIsNegInf(vx);
nan = VpIsNaN(vx);
break;
case T_FIXNUM:
/* fall through */
case T_BIGNUM:
vx = GetVpValue(x, 0);
break;
case T_FLOAT:
flo = RFLOAT_VALUE(x);
negative = flo < 0;
infinite = isinf(flo);
nan = isnan(flo);
if (!infinite && !nan) {
vx = GetVpValueWithPrec(x, 0, 0);
}
break;
case T_RATIONAL:
vx = GetVpValueWithPrec(x, prec, 0);
break;
default:
break;
}
if (infinite) {
if (negative) {
return VpCheckGetValue(GetVpValueWithPrec(INT2FIX(0), prec, 1));
}
else {
Real* vy;
vy = VpCreateRbObject(prec, "#0", true);
VpSetInf(vy, VP_SIGN_POSITIVE_INFINITE);
RB_GC_GUARD(vy->obj);
return VpCheckGetValue(vy);
}
}
else if (nan) {
Real* vy;
vy = VpCreateRbObject(prec, "#0", true);
VpSetNaN(vy);
RB_GC_GUARD(vy->obj);
return VpCheckGetValue(vy);
}
else if (vx == NULL) {
cannot_be_coerced_into_BigDecimal(rb_eArgError, x);
}
x = vx->obj;
n = prec + BIGDECIMAL_DOUBLE_FIGURES;
negative = BIGDECIMAL_NEGATIVE_P(vx);
if (negative) {
VALUE x_zero = INT2NUM(1);
VALUE x_copy = f_BigDecimal(1, &x_zero, klass);
x = BigDecimal_initialize_copy(x_copy, x);
vx = DATA_PTR(x);
VpSetSign(vx, 1);
}
one = VpCheckGetValue(VpCreateRbObject(1, "1", true));
y = one;
d = y;
i = 1;
while (!VpIsZero((Real*)DATA_PTR(d))) {
SIGNED_VALUE const ey = VpExponent10(DATA_PTR(y));
SIGNED_VALUE const ed = VpExponent10(DATA_PTR(d));
ssize_t m = n - vabs(ey - ed);
rb_thread_check_ints();
if (m <= 0) {
break;
}
else if ((size_t)m < BIGDECIMAL_DOUBLE_FIGURES) {
m = BIGDECIMAL_DOUBLE_FIGURES;
}
d = BigDecimal_mult(d, x); /* d <- d * x */
d = BigDecimal_div2(d, SSIZET2NUM(i), SSIZET2NUM(m)); /* d <- d / i */
y = BigDecimal_add(y, d); /* y <- y + d */
++i; /* i <- i + 1 */
}
if (negative) {
return BigDecimal_div2(one, y, vprec);
}
else {
vprec = SSIZET2NUM(prec - VpExponent10(DATA_PTR(y)));
return BigDecimal_round(1, &vprec, y);
}
RB_GC_GUARD(one);
RB_GC_GUARD(x);
RB_GC_GUARD(y);
RB_GC_GUARD(d);
}
/* call-seq:
* BigMath.log(decimal, numeric) -> BigDecimal
*
* Computes the natural logarithm of +decimal+ to the specified number of
* digits of precision, +numeric+.
*
* If +decimal+ is zero or negative, raises Math::DomainError.
*
* If +decimal+ is positive infinity, returns Infinity.
*
* If +decimal+ is NaN, returns NaN.
*/
static VALUE
BigMath_s_log(VALUE klass, VALUE x, VALUE vprec)
{
ssize_t prec, n, i;
SIGNED_VALUE expo;
Real* vx = NULL;
VALUE vn, one, two, w, x2, y, d;
int zero = 0;
int negative = 0;
int infinite = 0;
int nan = 0;
double flo;
long fix;
if (!is_integer(vprec)) {
rb_raise(rb_eArgError, "precision must be an Integer");
}
prec = NUM2SSIZET(vprec);
if (prec <= 0) {
rb_raise(rb_eArgError, "Zero or negative precision for exp");
}
/* TODO: the following switch statement is almost same as one in the
* BigDecimalCmp function. */
switch (TYPE(x)) {
case T_DATA:
if (!is_kind_of_BigDecimal(x)) break;
vx = DATA_PTR(x);
zero = VpIsZero(vx);
negative = BIGDECIMAL_NEGATIVE_P(vx);
infinite = VpIsPosInf(vx) || VpIsNegInf(vx);
nan = VpIsNaN(vx);
break;
case T_FIXNUM:
fix = FIX2LONG(x);
zero = fix == 0;
negative = fix < 0;
goto get_vp_value;
case T_BIGNUM:
i = FIX2INT(rb_big_cmp(x, INT2FIX(0)));
zero = i == 0;
negative = i < 0;
get_vp_value:
if (zero || negative) break;
vx = GetVpValue(x, 0);
break;
case T_FLOAT:
flo = RFLOAT_VALUE(x);
zero = flo == 0;
negative = flo < 0;
infinite = isinf(flo);
nan = isnan(flo);
if (!zero && !negative && !infinite && !nan) {
vx = GetVpValueWithPrec(x, 0, 1);
}
break;
case T_RATIONAL:
zero = RRATIONAL_ZERO_P(x);
negative = RRATIONAL_NEGATIVE_P(x);
if (zero || negative) break;
vx = GetVpValueWithPrec(x, prec, 1);
break;
case T_COMPLEX:
rb_raise(rb_eMathDomainError,
"Complex argument for BigMath.log");
default:
break;
}
if (infinite && !negative) {
Real* vy;
vy = VpCreateRbObject(prec, "#0", true);
RB_GC_GUARD(vy->obj);
VpSetInf(vy, VP_SIGN_POSITIVE_INFINITE);
return VpCheckGetValue(vy);
}
else if (nan) {
Real* vy;
vy = VpCreateRbObject(prec, "#0", true);
RB_GC_GUARD(vy->obj);
VpSetNaN(vy);
return VpCheckGetValue(vy);
}
else if (zero || negative) {
rb_raise(rb_eMathDomainError,
"Zero or negative argument for log");
}
else if (vx == NULL) {
cannot_be_coerced_into_BigDecimal(rb_eArgError, x);
}
x = VpCheckGetValue(vx);
RB_GC_GUARD(one) = VpCheckGetValue(VpCreateRbObject(1, "1", true));
RB_GC_GUARD(two) = VpCheckGetValue(VpCreateRbObject(1, "2", true));
n = prec + BIGDECIMAL_DOUBLE_FIGURES;
RB_GC_GUARD(vn) = SSIZET2NUM(n);
expo = VpExponent10(vx);
if (expo < 0 || expo >= 3) {
char buf[DECIMAL_SIZE_OF_BITS(SIZEOF_VALUE * CHAR_BIT) + 4];
snprintf(buf, sizeof(buf), "1E%"PRIdVALUE, -expo);
x = BigDecimal_mult2(x, VpCheckGetValue(VpCreateRbObject(1, buf, true)), vn);
}
else {
expo = 0;
}
w = BigDecimal_sub(x, one);
x = BigDecimal_div2(w, BigDecimal_add(x, one), vn);
RB_GC_GUARD(x2) = BigDecimal_mult2(x, x, vn);
RB_GC_GUARD(y) = x;
RB_GC_GUARD(d) = y;
i = 1;
while (!VpIsZero((Real*)DATA_PTR(d))) {
SIGNED_VALUE const ey = VpExponent10(DATA_PTR(y));
SIGNED_VALUE const ed = VpExponent10(DATA_PTR(d));
ssize_t m = n - vabs(ey - ed);
if (m <= 0) {
break;
}
else if ((size_t)m < BIGDECIMAL_DOUBLE_FIGURES) {
m = BIGDECIMAL_DOUBLE_FIGURES;
}
x = BigDecimal_mult2(x2, x, vn);
i += 2;
d = BigDecimal_div2(x, SSIZET2NUM(i), SSIZET2NUM(m));
y = BigDecimal_add(y, d);
}
y = BigDecimal_mult(y, two);
if (expo != 0) {
VALUE log10, vexpo, dy;
log10 = BigMath_s_log(klass, INT2FIX(10), vprec);
vexpo = VpCheckGetValue(GetVpValue(SSIZET2NUM(expo), 1));
dy = BigDecimal_mult(log10, vexpo);
y = BigDecimal_add(y, dy);
}
return y;
}
static VALUE BIGDECIMAL_NAN = Qnil;
static VALUE
BigDecimal_nan(void)
{
return BIGDECIMAL_NAN;
}
static VALUE BIGDECIMAL_POSITIVE_INFINITY = Qnil;
static VALUE
BigDecimal_positive_infinity(void)
{
return BIGDECIMAL_POSITIVE_INFINITY;
}
static VALUE BIGDECIMAL_NEGATIVE_INFINITY = Qnil;
static VALUE
BigDecimal_negative_infinity(void)
{
return BIGDECIMAL_NEGATIVE_INFINITY;
}
static VALUE BIGDECIMAL_POSITIVE_ZERO = Qnil;
static VALUE
BigDecimal_positive_zero(void)
{
return BIGDECIMAL_POSITIVE_ZERO;
}
static VALUE BIGDECIMAL_NEGATIVE_ZERO = Qnil;
static VALUE
BigDecimal_negative_zero(void)
{
return BIGDECIMAL_NEGATIVE_ZERO;
}
/* Document-class: BigDecimal
* BigDecimal provides arbitrary-precision floating point decimal arithmetic.
*
* == Introduction
*
* Ruby provides built-in support for arbitrary precision integer arithmetic.
*
* For example:
*
* 42**13 #=> 1265437718438866624512
*
* BigDecimal provides similar support for very large or very accurate floating
* point numbers.
*
* Decimal arithmetic is also useful for general calculation, because it
* provides the correct answers people expect--whereas normal binary floating
* point arithmetic often introduces subtle errors because of the conversion
* between base 10 and base 2.
*
* For example, try:
*
* sum = 0
* 10_000.times do
* sum = sum + 0.0001
* end
* print sum #=> 0.9999999999999062
*
* and contrast with the output from:
*
* require 'bigdecimal'
*
* sum = BigDecimal("0")
* 10_000.times do
* sum = sum + BigDecimal("0.0001")
* end
* print sum #=> 0.1E1
*
* Similarly:
*
* (BigDecimal("1.2") - BigDecimal("1.0")) == BigDecimal("0.2") #=> true
*
* (1.2 - 1.0) == 0.2 #=> false
*
* == A Note About Precision
*
* For a calculation using a \BigDecimal and another +value+,
* the precision of the result depends on the type of +value+:
*
* - If +value+ is a \Float,
* the precision is Float::DIG + 1.
* - If +value+ is a \Rational, the precision is larger than Float::DIG + 1.
* - If +value+ is a \BigDecimal, the precision is +value+'s precision in the
* internal representation, which is platform-dependent.
* - If +value+ is other object, the precision is determined by the result of +BigDecimal(value)+.
*
* == Special features of accurate decimal arithmetic
*
* Because BigDecimal is more accurate than normal binary floating point
* arithmetic, it requires some special values.
*
* === Infinity
*
* BigDecimal sometimes needs to return infinity, for example if you divide
* a value by zero.
*
* BigDecimal("1.0") / BigDecimal("0.0") #=> Infinity
* BigDecimal("-1.0") / BigDecimal("0.0") #=> -Infinity
*
* You can represent infinite numbers to BigDecimal using the strings
* <code>'Infinity'</code>, <code>'+Infinity'</code> and
* <code>'-Infinity'</code> (case-sensitive)
*
* === Not a Number
*
* When a computation results in an undefined value, the special value +NaN+
* (for 'not a number') is returned.
*
* Example:
*
* BigDecimal("0.0") / BigDecimal("0.0") #=> NaN
*
* You can also create undefined values.
*
* NaN is never considered to be the same as any other value, even NaN itself:
*
* n = BigDecimal('NaN')
* n == 0.0 #=> false
* n == n #=> false
*
* === Positive and negative zero
*
* If a computation results in a value which is too small to be represented as
* a BigDecimal within the currently specified limits of precision, zero must
* be returned.
*
* If the value which is too small to be represented is negative, a BigDecimal
* value of negative zero is returned.
*
* BigDecimal("1.0") / BigDecimal("-Infinity") #=> -0.0
*
* If the value is positive, a value of positive zero is returned.
*
* BigDecimal("1.0") / BigDecimal("Infinity") #=> 0.0
*
* (See BigDecimal.mode for how to specify limits of precision.)
*
* Note that +-0.0+ and +0.0+ are considered to be the same for the purposes of
* comparison.
*
* Note also that in mathematics, there is no particular concept of negative
* or positive zero; true mathematical zero has no sign.
*
* == bigdecimal/util
*
* When you require +bigdecimal/util+, the #to_d method will be
* available on BigDecimal and the native Integer, Float, Rational,
* and String classes:
*
* require 'bigdecimal/util'
*
* 42.to_d # => 0.42e2
* 0.5.to_d # => 0.5e0
* (2/3r).to_d(3) # => 0.667e0
* "0.5".to_d # => 0.5e0
*
* == License
*
* Copyright (C) 2002 by Shigeo Kobayashi <shigeo@tinyforest.gr.jp>.
*
* BigDecimal is released under the Ruby and 2-clause BSD licenses.
* See LICENSE.txt for details.
*
* Maintained by mrkn <mrkn@mrkn.jp> and ruby-core members.
*
* Documented by zzak <zachary@zacharyscott.net>, mathew <meta@pobox.com>, and
* many other contributors.
*/
void
Init_bigdecimal(void)
{
#ifdef HAVE_RB_EXT_RACTOR_SAFE
rb_ext_ractor_safe(true);
#endif
VALUE arg;
id_BigDecimal_exception_mode = rb_intern_const("BigDecimal.exception_mode");
id_BigDecimal_rounding_mode = rb_intern_const("BigDecimal.rounding_mode");
id_BigDecimal_precision_limit = rb_intern_const("BigDecimal.precision_limit");
/* Initialize VP routines */
VpInit(0UL);
/* Class and method registration */
rb_cBigDecimal = rb_define_class("BigDecimal", rb_cNumeric);
/* Global function */
rb_define_global_function("BigDecimal", f_BigDecimal, -1);
/* Class methods */
rb_undef_alloc_func(rb_cBigDecimal);
rb_undef_method(CLASS_OF(rb_cBigDecimal), "new");
rb_define_singleton_method(rb_cBigDecimal, "interpret_loosely", BigDecimal_s_interpret_loosely, 1);
rb_define_singleton_method(rb_cBigDecimal, "mode", BigDecimal_mode, -1);
rb_define_singleton_method(rb_cBigDecimal, "limit", BigDecimal_limit, -1);
rb_define_singleton_method(rb_cBigDecimal, "double_fig", BigDecimal_double_fig, 0);
rb_define_singleton_method(rb_cBigDecimal, "_load", BigDecimal_load, 1);
rb_define_singleton_method(rb_cBigDecimal, "save_exception_mode", BigDecimal_save_exception_mode, 0);
rb_define_singleton_method(rb_cBigDecimal, "save_rounding_mode", BigDecimal_save_rounding_mode, 0);
rb_define_singleton_method(rb_cBigDecimal, "save_limit", BigDecimal_save_limit, 0);
/* Constants definition */
#ifndef RUBY_BIGDECIMAL_VERSION
# error RUBY_BIGDECIMAL_VERSION is not defined
#endif
/*
* The version of bigdecimal library
*/
rb_define_const(rb_cBigDecimal, "VERSION", rb_str_new2(RUBY_BIGDECIMAL_VERSION));
/*
* Base value used in internal calculations. On a 32 bit system, BASE
* is 10000, indicating that calculation is done in groups of 4 digits.
* (If it were larger, BASE**2 wouldn't fit in 32 bits, so you couldn't
* guarantee that two groups could always be multiplied together without
* overflow.)
*/
rb_define_const(rb_cBigDecimal, "BASE", INT2FIX((SIGNED_VALUE)VpBaseVal()));
/* Exceptions */
/*
* 0xff: Determines whether overflow, underflow or zero divide result in
* an exception being thrown. See BigDecimal.mode.
*/
rb_define_const(rb_cBigDecimal, "EXCEPTION_ALL", INT2FIX(VP_EXCEPTION_ALL));
/*
* 0x02: Determines what happens when the result of a computation is not a
* number (NaN). See BigDecimal.mode.
*/
rb_define_const(rb_cBigDecimal, "EXCEPTION_NaN", INT2FIX(VP_EXCEPTION_NaN));
/*
* 0x01: Determines what happens when the result of a computation is
* infinity. See BigDecimal.mode.
*/
rb_define_const(rb_cBigDecimal, "EXCEPTION_INFINITY", INT2FIX(VP_EXCEPTION_INFINITY));
/*
* 0x04: Determines what happens when the result of a computation is an
* underflow (a result too small to be represented). See BigDecimal.mode.
*/
rb_define_const(rb_cBigDecimal, "EXCEPTION_UNDERFLOW", INT2FIX(VP_EXCEPTION_UNDERFLOW));
/*
* 0x01: Determines what happens when the result of a computation is an
* overflow (a result too large to be represented). See BigDecimal.mode.
*/
rb_define_const(rb_cBigDecimal, "EXCEPTION_OVERFLOW", INT2FIX(VP_EXCEPTION_OVERFLOW));
/*
* 0x10: Determines what happens when a division by zero is performed.
* See BigDecimal.mode.
*/
rb_define_const(rb_cBigDecimal, "EXCEPTION_ZERODIVIDE", INT2FIX(VP_EXCEPTION_ZERODIVIDE));
/*
* 0x100: Determines what happens when a result must be rounded in order to
* fit in the appropriate number of significant digits. See
* BigDecimal.mode.
*/
rb_define_const(rb_cBigDecimal, "ROUND_MODE", INT2FIX(VP_ROUND_MODE));
/* 1: Indicates that values should be rounded away from zero. See
* BigDecimal.mode.
*/
rb_define_const(rb_cBigDecimal, "ROUND_UP", INT2FIX(VP_ROUND_UP));
/* 2: Indicates that values should be rounded towards zero. See
* BigDecimal.mode.
*/
rb_define_const(rb_cBigDecimal, "ROUND_DOWN", INT2FIX(VP_ROUND_DOWN));
/* 3: Indicates that digits >= 5 should be rounded up, others rounded down.
* See BigDecimal.mode. */
rb_define_const(rb_cBigDecimal, "ROUND_HALF_UP", INT2FIX(VP_ROUND_HALF_UP));
/* 4: Indicates that digits >= 6 should be rounded up, others rounded down.
* See BigDecimal.mode.
*/
rb_define_const(rb_cBigDecimal, "ROUND_HALF_DOWN", INT2FIX(VP_ROUND_HALF_DOWN));
/* 5: Round towards +Infinity. See BigDecimal.mode. */
rb_define_const(rb_cBigDecimal, "ROUND_CEILING", INT2FIX(VP_ROUND_CEIL));
/* 6: Round towards -Infinity. See BigDecimal.mode. */
rb_define_const(rb_cBigDecimal, "ROUND_FLOOR", INT2FIX(VP_ROUND_FLOOR));
/* 7: Round towards the even neighbor. See BigDecimal.mode. */
rb_define_const(rb_cBigDecimal, "ROUND_HALF_EVEN", INT2FIX(VP_ROUND_HALF_EVEN));
/* 0: Indicates that a value is not a number. See BigDecimal.sign. */
rb_define_const(rb_cBigDecimal, "SIGN_NaN", INT2FIX(VP_SIGN_NaN));
/* 1: Indicates that a value is +0. See BigDecimal.sign. */
rb_define_const(rb_cBigDecimal, "SIGN_POSITIVE_ZERO", INT2FIX(VP_SIGN_POSITIVE_ZERO));
/* -1: Indicates that a value is -0. See BigDecimal.sign. */
rb_define_const(rb_cBigDecimal, "SIGN_NEGATIVE_ZERO", INT2FIX(VP_SIGN_NEGATIVE_ZERO));
/* 2: Indicates that a value is positive and finite. See BigDecimal.sign. */
rb_define_const(rb_cBigDecimal, "SIGN_POSITIVE_FINITE", INT2FIX(VP_SIGN_POSITIVE_FINITE));
/* -2: Indicates that a value is negative and finite. See BigDecimal.sign. */
rb_define_const(rb_cBigDecimal, "SIGN_NEGATIVE_FINITE", INT2FIX(VP_SIGN_NEGATIVE_FINITE));
/* 3: Indicates that a value is positive and infinite. See BigDecimal.sign. */
rb_define_const(rb_cBigDecimal, "SIGN_POSITIVE_INFINITE", INT2FIX(VP_SIGN_POSITIVE_INFINITE));
/* -3: Indicates that a value is negative and infinite. See BigDecimal.sign. */
rb_define_const(rb_cBigDecimal, "SIGN_NEGATIVE_INFINITE", INT2FIX(VP_SIGN_NEGATIVE_INFINITE));
/* Positive zero value. */
arg = rb_str_new2("+0");
BIGDECIMAL_POSITIVE_ZERO = f_BigDecimal(1, &arg, rb_cBigDecimal);
rb_gc_register_mark_object(BIGDECIMAL_POSITIVE_ZERO);
/* Negative zero value. */
arg = rb_str_new2("-0");
BIGDECIMAL_NEGATIVE_ZERO = f_BigDecimal(1, &arg, rb_cBigDecimal);
rb_gc_register_mark_object(BIGDECIMAL_NEGATIVE_ZERO);
/* Positive infinity value. */
arg = rb_str_new2("+Infinity");
BIGDECIMAL_POSITIVE_INFINITY = f_BigDecimal(1, &arg, rb_cBigDecimal);
rb_gc_register_mark_object(BIGDECIMAL_POSITIVE_INFINITY);
/* Negative infinity value. */
arg = rb_str_new2("-Infinity");
BIGDECIMAL_NEGATIVE_INFINITY = f_BigDecimal(1, &arg, rb_cBigDecimal);
rb_gc_register_mark_object(BIGDECIMAL_NEGATIVE_INFINITY);
/* 'Not a Number' value. */
arg = rb_str_new2("NaN");
BIGDECIMAL_NAN = f_BigDecimal(1, &arg, rb_cBigDecimal);
rb_gc_register_mark_object(BIGDECIMAL_NAN);
/* Special value constants */
rb_define_const(rb_cBigDecimal, "INFINITY", BIGDECIMAL_POSITIVE_INFINITY);
rb_define_const(rb_cBigDecimal, "NAN", BIGDECIMAL_NAN);
/* instance methods */
rb_define_method(rb_cBigDecimal, "precs", BigDecimal_prec, 0);
rb_define_method(rb_cBigDecimal, "precision", BigDecimal_precision, 0);
rb_define_method(rb_cBigDecimal, "scale", BigDecimal_scale, 0);
rb_define_method(rb_cBigDecimal, "precision_scale", BigDecimal_precision_scale, 0);
rb_define_method(rb_cBigDecimal, "n_significant_digits", BigDecimal_n_significant_digits, 0);
rb_define_method(rb_cBigDecimal, "add", BigDecimal_add2, 2);
rb_define_method(rb_cBigDecimal, "sub", BigDecimal_sub2, 2);
rb_define_method(rb_cBigDecimal, "mult", BigDecimal_mult2, 2);
rb_define_method(rb_cBigDecimal, "div", BigDecimal_div3, -1);
rb_define_method(rb_cBigDecimal, "hash", BigDecimal_hash, 0);
rb_define_method(rb_cBigDecimal, "to_s", BigDecimal_to_s, -1);
rb_define_method(rb_cBigDecimal, "to_i", BigDecimal_to_i, 0);
rb_define_method(rb_cBigDecimal, "to_int", BigDecimal_to_i, 0);
rb_define_method(rb_cBigDecimal, "to_r", BigDecimal_to_r, 0);
rb_define_method(rb_cBigDecimal, "split", BigDecimal_split, 0);
rb_define_method(rb_cBigDecimal, "+", BigDecimal_add, 1);
rb_define_method(rb_cBigDecimal, "-", BigDecimal_sub, 1);
rb_define_method(rb_cBigDecimal, "+@", BigDecimal_uplus, 0);
rb_define_method(rb_cBigDecimal, "-@", BigDecimal_neg, 0);
rb_define_method(rb_cBigDecimal, "*", BigDecimal_mult, 1);
rb_define_method(rb_cBigDecimal, "/", BigDecimal_div, 1);
rb_define_method(rb_cBigDecimal, "quo", BigDecimal_quo, -1);
rb_define_method(rb_cBigDecimal, "%", BigDecimal_mod, 1);
rb_define_method(rb_cBigDecimal, "modulo", BigDecimal_mod, 1);
rb_define_method(rb_cBigDecimal, "remainder", BigDecimal_remainder, 1);
rb_define_method(rb_cBigDecimal, "divmod", BigDecimal_divmod, 1);
rb_define_method(rb_cBigDecimal, "clone", BigDecimal_clone, 0);
rb_define_method(rb_cBigDecimal, "dup", BigDecimal_clone, 0);
rb_define_method(rb_cBigDecimal, "to_f", BigDecimal_to_f, 0);
rb_define_method(rb_cBigDecimal, "abs", BigDecimal_abs, 0);
rb_define_method(rb_cBigDecimal, "sqrt", BigDecimal_sqrt, 1);
rb_define_method(rb_cBigDecimal, "fix", BigDecimal_fix, 0);
rb_define_method(rb_cBigDecimal, "round", BigDecimal_round, -1);
rb_define_method(rb_cBigDecimal, "frac", BigDecimal_frac, 0);
rb_define_method(rb_cBigDecimal, "floor", BigDecimal_floor, -1);
rb_define_method(rb_cBigDecimal, "ceil", BigDecimal_ceil, -1);
rb_define_method(rb_cBigDecimal, "power", BigDecimal_power, -1);
rb_define_method(rb_cBigDecimal, "**", BigDecimal_power_op, 1);
rb_define_method(rb_cBigDecimal, "<=>", BigDecimal_comp, 1);
rb_define_method(rb_cBigDecimal, "==", BigDecimal_eq, 1);
rb_define_method(rb_cBigDecimal, "===", BigDecimal_eq, 1);
rb_define_method(rb_cBigDecimal, "eql?", BigDecimal_eq, 1);
rb_define_method(rb_cBigDecimal, "<", BigDecimal_lt, 1);
rb_define_method(rb_cBigDecimal, "<=", BigDecimal_le, 1);
rb_define_method(rb_cBigDecimal, ">", BigDecimal_gt, 1);
rb_define_method(rb_cBigDecimal, ">=", BigDecimal_ge, 1);
rb_define_method(rb_cBigDecimal, "zero?", BigDecimal_zero, 0);
rb_define_method(rb_cBigDecimal, "nonzero?", BigDecimal_nonzero, 0);
rb_define_method(rb_cBigDecimal, "coerce", BigDecimal_coerce, 1);
rb_define_method(rb_cBigDecimal, "inspect", BigDecimal_inspect, 0);
rb_define_method(rb_cBigDecimal, "exponent", BigDecimal_exponent, 0);
rb_define_method(rb_cBigDecimal, "sign", BigDecimal_sign, 0);
rb_define_method(rb_cBigDecimal, "nan?", BigDecimal_IsNaN, 0);
rb_define_method(rb_cBigDecimal, "infinite?", BigDecimal_IsInfinite, 0);
rb_define_method(rb_cBigDecimal, "finite?", BigDecimal_IsFinite, 0);
rb_define_method(rb_cBigDecimal, "truncate", BigDecimal_truncate, -1);
rb_define_method(rb_cBigDecimal, "_dump", BigDecimal_dump, -1);
rb_mBigMath = rb_define_module("BigMath");
rb_define_singleton_method(rb_mBigMath, "exp", BigMath_s_exp, 2);
rb_define_singleton_method(rb_mBigMath, "log", BigMath_s_log, 2);
id_up = rb_intern_const("up");
id_down = rb_intern_const("down");
id_truncate = rb_intern_const("truncate");
id_half_up = rb_intern_const("half_up");
id_default = rb_intern_const("default");
id_half_down = rb_intern_const("half_down");
id_half_even = rb_intern_const("half_even");
id_banker = rb_intern_const("banker");
id_ceiling = rb_intern_const("ceiling");
id_ceil = rb_intern_const("ceil");
id_floor = rb_intern_const("floor");
id_to_r = rb_intern_const("to_r");
id_eq = rb_intern_const("==");
id_half = rb_intern_const("half");
}
/*
*
* ============================================================================
*
* vp_ routines begin from here.
*
* ============================================================================
*
*/
#ifdef BIGDECIMAL_DEBUG
static int gfDebug = 1; /* Debug switch */
#if 0
static int gfCheckVal = 1; /* Value checking flag in VpNmlz() */
#endif
#endif /* BIGDECIMAL_DEBUG */
static Real *VpConstOne; /* constant 1.0 */
static Real *VpPt5; /* constant 0.5 */
#define maxnr 100UL /* Maximum iterations for calculating sqrt. */
/* used in VpSqrt() */
/* ETC */
#define MemCmp(x,y,z) memcmp(x,y,z)
#define StrCmp(x,y) strcmp(x,y)
enum op_sw {
OP_SW_ADD = 1, /* + */
OP_SW_SUB, /* - */
OP_SW_MULT, /* * */
OP_SW_DIV /* / */
};
static int VpIsDefOP(Real *c, Real *a, Real *b, enum op_sw sw);
static int AddExponent(Real *a, SIGNED_VALUE n);
static DECDIG VpAddAbs(Real *a,Real *b,Real *c);
static DECDIG VpSubAbs(Real *a,Real *b,Real *c);
static size_t VpSetPTR(Real *a, Real *b, Real *c, size_t *a_pos, size_t *b_pos, size_t *c_pos, DECDIG *av, DECDIG *bv);
static int VpNmlz(Real *a);
static void VpFormatSt(char *psz, size_t fFmt);
static int VpRdup(Real *m, size_t ind_m);
#ifdef BIGDECIMAL_DEBUG
# ifdef HAVE_RB_EXT_RACTOR_SAFE
# error Need to make rewiting gnAlloc atomic
# endif
static int gnAlloc = 0; /* Memory allocation counter */
#endif /* BIGDECIMAL_DEBUG */
VP_EXPORT void *
VpMemAlloc(size_t mb)
{
void *p = xmalloc(mb);
memset(p, 0, mb);
#ifdef BIGDECIMAL_DEBUG
gnAlloc++; /* Count allocation call */
#endif /* BIGDECIMAL_DEBUG */
return p;
}
VP_EXPORT void *
VpMemRealloc(void *ptr, size_t mb)
{
return xrealloc(ptr, mb);
}
VP_EXPORT void
VpFree(Real *pv)
{
if (pv != NULL) {
xfree(pv);
#ifdef BIGDECIMAL_DEBUG
gnAlloc--; /* Decrement allocation count */
if (gnAlloc == 0) {
printf(" *************** All memories allocated freed ****************\n");
/*getchar();*/
}
if (gnAlloc < 0) {
printf(" ??????????? Too many memory free calls(%d) ?????????????\n", gnAlloc);
/*getchar();*/
}
#endif /* BIGDECIMAL_DEBUG */
}
}
/*
* EXCEPTION Handling.
*/
#define bigdecimal_set_thread_local_exception_mode(mode) \
rb_thread_local_aset( \
rb_thread_current(), \
id_BigDecimal_exception_mode, \
INT2FIX((int)(mode)) \
)
static unsigned short
VpGetException (void)
{
VALUE const vmode = rb_thread_local_aref(
rb_thread_current(),
id_BigDecimal_exception_mode
);
if (NIL_P(vmode)) {
bigdecimal_set_thread_local_exception_mode(BIGDECIMAL_EXCEPTION_MODE_DEFAULT);
return BIGDECIMAL_EXCEPTION_MODE_DEFAULT;
}
return NUM2USHORT(vmode);
}
static void
VpSetException(unsigned short f)
{
bigdecimal_set_thread_local_exception_mode(f);
}
static void
VpCheckException(Real *p, bool always)
{
if (VpIsNaN(p)) {
VpException(VP_EXCEPTION_NaN, "Computation results in 'NaN' (Not a Number)", always);
}
else if (VpIsPosInf(p)) {
VpException(VP_EXCEPTION_INFINITY, "Computation results in 'Infinity'", always);
}
else if (VpIsNegInf(p)) {
VpException(VP_EXCEPTION_INFINITY, "Computation results in '-Infinity'", always);
}
}
static VALUE
VpCheckGetValue(Real *p)
{
VpCheckException(p, false);
return p->obj;
}
/*
* Precision limit.
*/
#define bigdecimal_set_thread_local_precision_limit(limit) \
rb_thread_local_aset( \
rb_thread_current(), \
id_BigDecimal_precision_limit, \
SIZET2NUM(limit) \
)
#define BIGDECIMAL_PRECISION_LIMIT_DEFAULT ((size_t)0)
/* These 2 functions added at v1.1.7 */
VP_EXPORT size_t
VpGetPrecLimit(void)
{
VALUE const vlimit = rb_thread_local_aref(
rb_thread_current(),
id_BigDecimal_precision_limit
);
if (NIL_P(vlimit)) {
bigdecimal_set_thread_local_precision_limit(BIGDECIMAL_PRECISION_LIMIT_DEFAULT);
return BIGDECIMAL_PRECISION_LIMIT_DEFAULT;
}
return NUM2SIZET(vlimit);
}
VP_EXPORT size_t
VpSetPrecLimit(size_t n)
{
size_t const s = VpGetPrecLimit();
bigdecimal_set_thread_local_precision_limit(n);
return s;
}
/*
* Rounding mode.
*/
#define bigdecimal_set_thread_local_rounding_mode(mode) \
rb_thread_local_aset( \
rb_thread_current(), \
id_BigDecimal_rounding_mode, \
INT2FIX((int)(mode)) \
)
VP_EXPORT unsigned short
VpGetRoundMode(void)
{
VALUE const vmode = rb_thread_local_aref(
rb_thread_current(),
id_BigDecimal_rounding_mode
);
if (NIL_P(vmode)) {
bigdecimal_set_thread_local_rounding_mode(BIGDECIMAL_ROUNDING_MODE_DEFAULT);
return BIGDECIMAL_ROUNDING_MODE_DEFAULT;
}
return NUM2USHORT(vmode);
}
VP_EXPORT int
VpIsRoundMode(unsigned short n)
{
switch (n) {
case VP_ROUND_UP:
case VP_ROUND_DOWN:
case VP_ROUND_HALF_UP:
case VP_ROUND_HALF_DOWN:
case VP_ROUND_CEIL:
case VP_ROUND_FLOOR:
case VP_ROUND_HALF_EVEN:
return 1;
default:
return 0;
}
}
VP_EXPORT unsigned short
VpSetRoundMode(unsigned short n)
{
if (VpIsRoundMode(n)) {
bigdecimal_set_thread_local_rounding_mode(n);
return n;
}
return VpGetRoundMode();
}
/*
* 0.0 & 1.0 generator
* These gZero_..... and gOne_..... can be any name
* referenced from nowhere except Zero() and One().
* gZero_..... and gOne_..... must have global scope
* (to let the compiler know they may be changed in outside
* (... but not actually..)).
*/
volatile const double gOne_ABCED9B4_CE73__00400511F31D = 1.0;
static double
One(void)
{
return gOne_ABCED9B4_CE73__00400511F31D;
}
/*
----------------------------------------------------------------
Value of sign in Real structure is reserved for future use.
short sign;
==0 : NaN
1 : Positive zero
-1 : Negative zero
2 : Positive number
-2 : Negative number
3 : Positive infinite number
-3 : Negative infinite number
----------------------------------------------------------------
*/
VP_EXPORT double
VpGetDoubleNaN(void) /* Returns the value of NaN */
{
return nan("");
}
VP_EXPORT double
VpGetDoublePosInf(void) /* Returns the value of +Infinity */
{
return HUGE_VAL;
}
VP_EXPORT double
VpGetDoubleNegInf(void) /* Returns the value of -Infinity */
{
return -HUGE_VAL;
}
VP_EXPORT double
VpGetDoubleNegZero(void) /* Returns the value of -0 */
{
static double nzero = 1000.0;
if (nzero != 0.0) nzero = (One()/VpGetDoubleNegInf());
return nzero;
}
#if 0 /* unused */
VP_EXPORT int
VpIsNegDoubleZero(double v)
{
double z = VpGetDoubleNegZero();
return MemCmp(&v,&z,sizeof(v))==0;
}
#endif
VP_EXPORT int
VpException(unsigned short f, const char *str,int always)
{
unsigned short const exception_mode = VpGetException();
if (f == VP_EXCEPTION_OP) always = 1;
if (always || (exception_mode & f)) {
switch(f) {
/* case VP_EXCEPTION_OVERFLOW: */
case VP_EXCEPTION_ZERODIVIDE:
case VP_EXCEPTION_INFINITY:
case VP_EXCEPTION_NaN:
case VP_EXCEPTION_UNDERFLOW:
case VP_EXCEPTION_OP:
rb_raise(rb_eFloatDomainError, "%s", str);
break;
default:
rb_fatal("%s", str);
}
}
return 0; /* 0 Means VpException() raised no exception */
}
/* Throw exception or returns 0,when resulting c is Inf or NaN */
/* sw=1:+ 2:- 3:* 4:/ */
static int
VpIsDefOP(Real *c, Real *a, Real *b, enum op_sw sw)
{
if (VpIsNaN(a) || VpIsNaN(b)) {
/* at least a or b is NaN */
VpSetNaN(c);
goto NaN;
}
if (VpIsInf(a)) {
if (VpIsInf(b)) {
switch(sw) {
case OP_SW_ADD: /* + */
if (VpGetSign(a) == VpGetSign(b)) {
VpSetInf(c, VpGetSign(a));
goto Inf;
}
else {
VpSetNaN(c);
goto NaN;
}
case OP_SW_SUB: /* - */
if (VpGetSign(a) != VpGetSign(b)) {
VpSetInf(c, VpGetSign(a));
goto Inf;
}
else {
VpSetNaN(c);
goto NaN;
}
case OP_SW_MULT: /* * */
VpSetInf(c, VpGetSign(a)*VpGetSign(b));
goto Inf;
case OP_SW_DIV: /* / */
VpSetNaN(c);
goto NaN;
}
VpSetNaN(c);
goto NaN;
}
/* Inf op Finite */
switch(sw) {
case OP_SW_ADD: /* + */
case OP_SW_SUB: /* - */
VpSetInf(c, VpGetSign(a));
break;
case OP_SW_MULT: /* * */
if (VpIsZero(b)) {
VpSetNaN(c);
goto NaN;
}
VpSetInf(c, VpGetSign(a)*VpGetSign(b));
break;
case OP_SW_DIV: /* / */
VpSetInf(c, VpGetSign(a)*VpGetSign(b));
}
goto Inf;
}
if (VpIsInf(b)) {
switch(sw) {
case OP_SW_ADD: /* + */
VpSetInf(c, VpGetSign(b));
break;
case OP_SW_SUB: /* - */
VpSetInf(c, -VpGetSign(b));
break;
case OP_SW_MULT: /* * */
if (VpIsZero(a)) {
VpSetNaN(c);
goto NaN;
}
VpSetInf(c, VpGetSign(a)*VpGetSign(b));
break;
case OP_SW_DIV: /* / */
VpSetZero(c, VpGetSign(a)*VpGetSign(b));
}
goto Inf;
}
return 1; /* Results OK */
Inf:
if (VpIsPosInf(c)) {
return VpException(VP_EXCEPTION_INFINITY, "Computation results to 'Infinity'", 0);
}
else {
return VpException(VP_EXCEPTION_INFINITY, "Computation results to '-Infinity'", 0);
}
NaN:
return VpException(VP_EXCEPTION_NaN, "Computation results to 'NaN'", 0);
}
/*
----------------------------------------------------------------
*/
/*
* returns number of chars needed to represent vp in specified format.
*/
VP_EXPORT size_t
VpNumOfChars(Real *vp,const char *pszFmt)
{
SIGNED_VALUE ex;
size_t nc;
if (vp == NULL) return BASE_FIG*2+6;
if (!VpIsDef(vp)) return 32; /* not sure,may be OK */
switch(*pszFmt) {
case 'F':
nc = BASE_FIG*(vp->Prec + 1)+2;
ex = vp->exponent;
if (ex < 0) {
nc += BASE_FIG*(size_t)(-ex);
}
else {
if ((size_t)ex > vp->Prec) {
nc += BASE_FIG*((size_t)ex - vp->Prec);
}
}
break;
case 'E':
/* fall through */
default:
nc = BASE_FIG*(vp->Prec + 2)+6; /* 3: sign + exponent chars */
}
return nc;
}
/*
* Initializer for Vp routines and constants used.
* [Input]
* BaseVal: Base value(assigned to BASE) for Vp calculation.
* It must be the form BaseVal=10**n.(n=1,2,3,...)
* If Base <= 0L,then the BASE will be calculated so
* that BASE is as large as possible satisfying the
* relation MaxVal <= BASE*(BASE+1). Where the value
* MaxVal is the largest value which can be represented
* by one DECDIG word in the computer used.
*
* [Returns]
* BIGDECIMAL_DOUBLE_FIGURES ... OK
*/
VP_EXPORT size_t
VpInit(DECDIG BaseVal)
{
/* Setup +/- Inf NaN -0 */
VpGetDoubleNegZero();
/* Allocates Vp constants. */
VpConstOne = VpAlloc(1UL, "1", 1, 1);
VpPt5 = VpAlloc(1UL, ".5", 1, 1);
#ifdef BIGDECIMAL_DEBUG
gnAlloc = 0;
#endif /* BIGDECIMAL_DEBUG */
#ifdef BIGDECIMAL_DEBUG
if (gfDebug) {
printf("VpInit: BaseVal = %"PRIuDECDIG"\n", BaseVal);
printf("\tBASE = %"PRIuDECDIG"\n", BASE);
printf("\tHALF_BASE = %"PRIuDECDIG"\n", HALF_BASE);
printf("\tBASE1 = %"PRIuDECDIG"\n", BASE1);
printf("\tBASE_FIG = %u\n", BASE_FIG);
printf("\tBIGDECIMAL_DOUBLE_FIGURES = %d\n", BIGDECIMAL_DOUBLE_FIGURES);
}
#endif /* BIGDECIMAL_DEBUG */
return BIGDECIMAL_DOUBLE_FIGURES;
}
VP_EXPORT Real *
VpOne(void)
{
return VpConstOne;
}
/* If exponent overflows,then raise exception or returns 0 */
static int
AddExponent(Real *a, SIGNED_VALUE n)
{
SIGNED_VALUE e = a->exponent;
SIGNED_VALUE m = e+n;
SIGNED_VALUE eb, mb;
if (e > 0) {
if (n > 0) {
if (MUL_OVERFLOW_SIGNED_VALUE_P(m, (SIGNED_VALUE)BASE_FIG) ||
MUL_OVERFLOW_SIGNED_VALUE_P(e, (SIGNED_VALUE)BASE_FIG))
goto overflow;
mb = m*(SIGNED_VALUE)BASE_FIG;
eb = e*(SIGNED_VALUE)BASE_FIG;
if (eb - mb > 0) goto overflow;
}
}
else if (n < 0) {
if (MUL_OVERFLOW_SIGNED_VALUE_P(m, (SIGNED_VALUE)BASE_FIG) ||
MUL_OVERFLOW_SIGNED_VALUE_P(e, (SIGNED_VALUE)BASE_FIG))
goto underflow;
mb = m*(SIGNED_VALUE)BASE_FIG;
eb = e*(SIGNED_VALUE)BASE_FIG;
if (mb - eb > 0) goto underflow;
}
a->exponent = m;
return 1;
/* Overflow/Underflow ==> Raise exception or returns 0 */
underflow:
VpSetZero(a, VpGetSign(a));
return VpException(VP_EXCEPTION_UNDERFLOW, "Exponent underflow", 0);
overflow:
VpSetInf(a, VpGetSign(a));
return VpException(VP_EXCEPTION_OVERFLOW, "Exponent overflow", 0);
}
Real *
bigdecimal_parse_special_string(const char *str)
{
static const struct {
const char *str;
size_t len;
int sign;
} table[] = {
{ SZ_INF, sizeof(SZ_INF) - 1, VP_SIGN_POSITIVE_INFINITE },
{ SZ_PINF, sizeof(SZ_PINF) - 1, VP_SIGN_POSITIVE_INFINITE },
{ SZ_NINF, sizeof(SZ_NINF) - 1, VP_SIGN_NEGATIVE_INFINITE },
{ SZ_NaN, sizeof(SZ_NaN) - 1, VP_SIGN_NaN }
};
static const size_t table_length = sizeof(table) / sizeof(table[0]);
size_t i;
for (i = 0; i < table_length; ++i) {
const char *p;
if (strncmp(str, table[i].str, table[i].len) != 0) {
continue;
}
p = str + table[i].len;
while (*p && ISSPACE(*p)) ++p;
if (*p == '\0') {
Real *vp = VpAllocReal(1);
vp->MaxPrec = 1;
switch (table[i].sign) {
default:
UNREACHABLE; break;
case VP_SIGN_POSITIVE_INFINITE:
VpSetPosInf(vp);
return vp;
case VP_SIGN_NEGATIVE_INFINITE:
VpSetNegInf(vp);
return vp;
case VP_SIGN_NaN:
VpSetNaN(vp);
return vp;
}
}
}
return NULL;
}
/*
* Allocates variable.
* [Input]
* mx ... allocation unit, if zero then mx is determined by szVal.
* The mx is the number of effective digits can to be stored.
* szVal ... value assigned(char). If szVal==NULL,then zero is assumed.
* If szVal[0]=='#' then Max. Prec. will not be considered(1.1.7),
* full precision specified by szVal is allocated.
*
* [Returns]
* Pointer to the newly allocated variable, or
* NULL be returned if memory allocation is failed,or any error.
*/
VP_EXPORT Real *
VpAlloc(size_t mx, const char *szVal, int strict_p, int exc)
{
const char *orig_szVal = szVal;
size_t i, j, ni, ipf, nf, ipe, ne, dot_seen, exp_seen, nalloc;
char v, *psz;
int sign=1;
Real *vp = NULL;
size_t mf = VpGetPrecLimit();
VALUE buf;
mx = (mx + BASE_FIG - 1) / BASE_FIG; /* Determine allocation unit. */
if (mx == 0) ++mx;
if (szVal) {
/* Skipping leading spaces */
while (ISSPACE(*szVal)) szVal++;
/* Processing the leading one `#` */
if (*szVal != '#') {
if (mf) {
mf = (mf + BASE_FIG - 1) / BASE_FIG + 2; /* Needs 1 more for div */
if (mx > mf) {
mx = mf;
}
}
}
else {
++szVal;
}
}
else {
return_zero:
/* necessary to be able to store */
/* at least mx digits. */
/* szVal==NULL ==> allocate zero value. */
vp = VpAllocReal(mx);
vp->MaxPrec = mx; /* set max precision */
VpSetZero(vp, 1); /* initialize vp to zero. */
return vp;
}
/* Check on Inf & NaN */
if ((vp = bigdecimal_parse_special_string(szVal)) != NULL) {
return vp;
}
/* Scanning digits */
/* A buffer for keeping scanned digits */
buf = rb_str_tmp_new(strlen(szVal) + 1);
psz = RSTRING_PTR(buf);
/* cursor: i for psz, and j for szVal */
i = j = 0;
/* Scanning: sign part */
v = psz[i] = szVal[j];
if ((v == '-') || (v == '+')) {
sign = -(v == '-');
++i;
++j;
}
/* Scanning: integer part */
ni = 0; /* number of digits in the integer part */
while ((v = psz[i] = szVal[j]) != '\0') {
if (!strict_p && ISSPACE(v)) {
v = psz[i] = '\0';
break;
}
if (v == '_') {
if (ni > 0) {
v = szVal[j+1];
if (v == '\0' || ISSPACE(v) || ISDIGIT(v)) {
++j;
continue;
}
if (!strict_p) {
v = psz[i] = '\0';
break;
}
}
goto invalid_value;
}
if (!ISDIGIT(v)) {
break;
}
++ni;
++i;
++j;
}
/* Scanning: fractional part */
nf = 0; /* number of digits in the fractional part */
ne = 0; /* number of digits in the exponential part */
ipf = 0; /* index of the beginning of the fractional part */
ipe = 0; /* index of the beginning of the exponential part */
dot_seen = 0;
exp_seen = 0;
if (v != '\0') {
/* Scanning fractional part */
if ((psz[i] = szVal[j]) == '.') {
dot_seen = 1;
++i;
++j;
ipf = i;
while ((v = psz[i] = szVal[j]) != '\0') {
if (!strict_p && ISSPACE(v)) {
v = psz[i] = '\0';
break;
}
if (v == '_') {
if (nf > 0 && ISDIGIT(szVal[j+1])) {
++j;
continue;
}
if (!strict_p) {
v = psz[i] = '\0';
if (nf == 0) {
dot_seen = 0;
}
break;
}
goto invalid_value;
}
if (!ISDIGIT(v)) break;
++i;
++j;
++nf;
}
}
/* Scanning exponential part */
if (v != '\0') {
switch ((psz[i] = szVal[j])) {
case '\0':
break;
case 'e': case 'E':
case 'd': case 'D':
exp_seen = 1;
++i;
++j;
ipe = i;
v = psz[i] = szVal[j];
if ((v == '-') || (v == '+')) {
++i;
++j;
}
while ((v = psz[i] = szVal[j]) != '\0') {
if (!strict_p && ISSPACE(v)) {
v = psz[i] = '\0';
break;
}
if (v == '_') {
if (ne > 0 && ISDIGIT(szVal[j+1])) {
++j;
continue;
}
if (!strict_p) {
v = psz[i] = '\0';
if (ne == 0) {
exp_seen = 0;
}
break;
}
goto invalid_value;
}
if (!ISDIGIT(v)) break;
++i;
++j;
++ne;
}
break;
default:
break;
}
}
if (v != '\0') {
/* Scanning trailing spaces */
while (ISSPACE(szVal[j])) ++j;
/* Invalid character */
if (szVal[j] && strict_p) {
goto invalid_value;
}
}
}
psz[i] = '\0';
if (strict_p && (((ni == 0 || dot_seen) && nf == 0) || (exp_seen && ne == 0))) {
VALUE str;
invalid_value:
if (!strict_p) {
goto return_zero;
}
if (!exc) {
return NULL;
}
str = rb_str_new2(orig_szVal);
rb_raise(rb_eArgError, "invalid value for BigDecimal(): \"%"PRIsVALUE"\"", str);
}
nalloc = (ni + nf + BASE_FIG - 1) / BASE_FIG + 1; /* set effective allocation */
/* units for szVal[] */
if (mx == 0) mx = 1;
nalloc = Max(nalloc, mx);
mx = nalloc;
vp = VpAllocReal(mx);
vp->MaxPrec = mx; /* set max precision */
VpSetZero(vp, sign);
VpCtoV(vp, psz, ni, psz + ipf, nf, psz + ipe, ne);
rb_str_resize(buf, 0);
return vp;
}
/*
* Assignment(c=a).
* [Input]
* a ... RHSV
* isw ... switch for assignment.
* c = a when isw > 0
* c = -a when isw < 0
* if c->MaxPrec < a->Prec,then round operation
* will be performed.
* [Output]
* c ... LHSV
*/
VP_EXPORT size_t
VpAsgn(Real *c, Real *a, int isw)
{
size_t n;
if (VpIsNaN(a)) {
VpSetNaN(c);
return 0;
}
if (VpIsInf(a)) {
VpSetInf(c, isw * VpGetSign(a));
return 0;
}
/* check if the RHS is zero */
if (!VpIsZero(a)) {
c->exponent = a->exponent; /* store exponent */
VpSetSign(c, isw * VpGetSign(a)); /* set sign */
n = (a->Prec < c->MaxPrec) ? (a->Prec) : (c->MaxPrec);
c->Prec = n;
memcpy(c->frac, a->frac, n * sizeof(DECDIG));
/* Needs round ? */
if (isw != 10) {
/* Not in ActiveRound */
if(c->Prec < a->Prec) {
VpInternalRound(c, n, (n>0) ? a->frac[n-1] : 0, a->frac[n]);
}
else {
VpLimitRound(c,0);
}
}
}
else {
/* The value of 'a' is zero. */
VpSetZero(c, isw * VpGetSign(a));
return 1;
}
return c->Prec * BASE_FIG;
}
/*
* c = a + b when operation = 1 or 2
* c = a - b when operation = -1 or -2.
* Returns number of significant digits of c
*/
VP_EXPORT size_t
VpAddSub(Real *c, Real *a, Real *b, int operation)
{
short sw, isw;
Real *a_ptr, *b_ptr;
size_t n, na, nb, i;
DECDIG mrv;
#ifdef BIGDECIMAL_DEBUG
if (gfDebug) {
VPrint(stdout, "VpAddSub(enter) a=% \n", a);
VPrint(stdout, " b=% \n", b);
printf(" operation=%d\n", operation);
}
#endif /* BIGDECIMAL_DEBUG */
if (!VpIsDefOP(c, a, b, (operation > 0) ? OP_SW_ADD : OP_SW_SUB)) return 0; /* No significant digits */
/* check if a or b is zero */
if (VpIsZero(a)) {
/* a is zero,then assign b to c */
if (!VpIsZero(b)) {
VpAsgn(c, b, operation);
}
else {
/* Both a and b are zero. */
if (VpGetSign(a) < 0 && operation * VpGetSign(b) < 0) {
/* -0 -0 */
VpSetZero(c, -1);
}
else {
VpSetZero(c, 1);
}
return 1; /* 0: 1 significant digits */
}
return c->Prec * BASE_FIG;
}
if (VpIsZero(b)) {
/* b is zero,then assign a to c. */
VpAsgn(c, a, 1);
return c->Prec*BASE_FIG;
}
if (operation < 0) sw = -1;
else sw = 1;
/* compare absolute value. As a result,|a_ptr|>=|b_ptr| */
if (a->exponent > b->exponent) {
a_ptr = a;
b_ptr = b;
} /* |a|>|b| */
else if (a->exponent < b->exponent) {
a_ptr = b;
b_ptr = a;
} /* |a|<|b| */
else {
/* Exponent part of a and b is the same,then compare fraction */
/* part */
na = a->Prec;
nb = b->Prec;
n = Min(na, nb);
for (i=0; i < n; ++i) {
if (a->frac[i] > b->frac[i]) {
a_ptr = a;
b_ptr = b;
goto end_if;
}
else if (a->frac[i] < b->frac[i]) {
a_ptr = b;
b_ptr = a;
goto end_if;
}
}
if (na > nb) {
a_ptr = a;
b_ptr = b;
goto end_if;
}
else if (na < nb) {
a_ptr = b;
b_ptr = a;
goto end_if;
}
/* |a| == |b| */
if (VpGetSign(a) + sw *VpGetSign(b) == 0) {
VpSetZero(c, 1); /* abs(a)=abs(b) and operation = '-' */
return c->Prec * BASE_FIG;
}
a_ptr = a;
b_ptr = b;
}
end_if:
isw = VpGetSign(a) + sw *VpGetSign(b);
/*
* isw = 0 ...( 1)+(-1),( 1)-( 1),(-1)+(1),(-1)-(-1)
* = 2 ...( 1)+( 1),( 1)-(-1)
* =-2 ...(-1)+(-1),(-1)-( 1)
* If isw==0, then c =(Sign a_ptr)(|a_ptr|-|b_ptr|)
* else c =(Sign ofisw)(|a_ptr|+|b_ptr|)
*/
if (isw) { /* addition */
VpSetSign(c, 1);
mrv = VpAddAbs(a_ptr, b_ptr, c);
VpSetSign(c, isw / 2);
}
else { /* subtraction */
VpSetSign(c, 1);
mrv = VpSubAbs(a_ptr, b_ptr, c);
if (a_ptr == a) {
VpSetSign(c,VpGetSign(a));
}
else {
VpSetSign(c, VpGetSign(a_ptr) * sw);
}
}
VpInternalRound(c, 0, (c->Prec > 0) ? c->frac[c->Prec-1] : 0, mrv);
#ifdef BIGDECIMAL_DEBUG
if (gfDebug) {
VPrint(stdout, "VpAddSub(result) c=% \n", c);
VPrint(stdout, " a=% \n", a);
VPrint(stdout, " b=% \n", b);
printf(" operation=%d\n", operation);
}
#endif /* BIGDECIMAL_DEBUG */
return c->Prec * BASE_FIG;
}
/*
* Addition of two values with variable precision
* a and b assuming abs(a)>abs(b).
* c = abs(a) + abs(b) ; where |a|>=|b|
*/
static DECDIG
VpAddAbs(Real *a, Real *b, Real *c)
{
size_t word_shift;
size_t ap;
size_t bp;
size_t cp;
size_t a_pos;
size_t b_pos, b_pos_with_word_shift;
size_t c_pos;
DECDIG av, bv, carry, mrv;
#ifdef BIGDECIMAL_DEBUG
if (gfDebug) {
VPrint(stdout, "VpAddAbs called: a = %\n", a);
VPrint(stdout, " b = %\n", b);
}
#endif /* BIGDECIMAL_DEBUG */
word_shift = VpSetPTR(a, b, c, &ap, &bp, &cp, &av, &bv);
a_pos = ap;
b_pos = bp;
c_pos = cp;
if (word_shift == (size_t)-1L) return 0; /* Overflow */
if (b_pos == (size_t)-1L) goto Assign_a;
mrv = av + bv; /* Most right val. Used for round. */
/* Just assign the last few digits of b to c because a has no */
/* corresponding digits to be added. */
if (b_pos > 0) {
while (b_pos > 0 && b_pos + word_shift > a_pos) {
c->frac[--c_pos] = b->frac[--b_pos];
}
}
if (b_pos == 0 && word_shift > a_pos) {
while (word_shift-- > a_pos) {
c->frac[--c_pos] = 0;
}
}
/* Just assign the last few digits of a to c because b has no */
/* corresponding digits to be added. */
b_pos_with_word_shift = b_pos + word_shift;
while (a_pos > b_pos_with_word_shift) {
c->frac[--c_pos] = a->frac[--a_pos];
}
carry = 0; /* set first carry be zero */
/* Now perform addition until every digits of b will be */
/* exhausted. */
while (b_pos > 0) {
c->frac[--c_pos] = a->frac[--a_pos] + b->frac[--b_pos] + carry;
if (c->frac[c_pos] >= BASE) {
c->frac[c_pos] -= BASE;
carry = 1;
}
else {
carry = 0;
}
}
/* Just assign the first few digits of a with considering */
/* the carry obtained so far because b has been exhausted. */
while (a_pos > 0) {
c->frac[--c_pos] = a->frac[--a_pos] + carry;
if (c->frac[c_pos] >= BASE) {
c->frac[c_pos] -= BASE;
carry = 1;
}
else {
carry = 0;
}
}
if (c_pos) c->frac[c_pos - 1] += carry;
goto Exit;
Assign_a:
VpAsgn(c, a, 1);
mrv = 0;
Exit:
#ifdef BIGDECIMAL_DEBUG
if (gfDebug) {
VPrint(stdout, "VpAddAbs exit: c=% \n", c);
}
#endif /* BIGDECIMAL_DEBUG */
return mrv;
}
/*
* c = abs(a) - abs(b)
*/
static DECDIG
VpSubAbs(Real *a, Real *b, Real *c)
{
size_t word_shift;
size_t ap;
size_t bp;
size_t cp;
size_t a_pos;
size_t b_pos, b_pos_with_word_shift;
size_t c_pos;
DECDIG av, bv, borrow, mrv;
#ifdef BIGDECIMAL_DEBUG
if (gfDebug) {
VPrint(stdout, "VpSubAbs called: a = %\n", a);
VPrint(stdout, " b = %\n", b);
}
#endif /* BIGDECIMAL_DEBUG */
word_shift = VpSetPTR(a, b, c, &ap, &bp, &cp, &av, &bv);
a_pos = ap;
b_pos = bp;
c_pos = cp;
if (word_shift == (size_t)-1L) return 0; /* Overflow */
if (b_pos == (size_t)-1L) goto Assign_a;
if (av >= bv) {
mrv = av - bv;
borrow = 0;
}
else {
mrv = 0;
borrow = 1;
}
/* Just assign the values which are the BASE subtracted by */
/* each of the last few digits of the b because the a has no */
/* corresponding digits to be subtracted. */
if (b_pos + word_shift > a_pos) {
while (b_pos > 0 && b_pos + word_shift > a_pos) {
c->frac[--c_pos] = BASE - b->frac[--b_pos] - borrow;
borrow = 1;
}
if (b_pos == 0) {
while (word_shift > a_pos) {
--word_shift;
c->frac[--c_pos] = BASE - borrow;
borrow = 1;
}
}
}
/* Just assign the last few digits of a to c because b has no */
/* corresponding digits to subtract. */
b_pos_with_word_shift = b_pos + word_shift;
while (a_pos > b_pos_with_word_shift) {
c->frac[--c_pos] = a->frac[--a_pos];
}
/* Now perform subtraction until every digits of b will be */
/* exhausted. */
while (b_pos > 0) {
--c_pos;
if (a->frac[--a_pos] < b->frac[--b_pos] + borrow) {
c->frac[c_pos] = BASE + a->frac[a_pos] - b->frac[b_pos] - borrow;
borrow = 1;
}
else {
c->frac[c_pos] = a->frac[a_pos] - b->frac[b_pos] - borrow;
borrow = 0;
}
}
/* Just assign the first few digits of a with considering */
/* the borrow obtained so far because b has been exhausted. */
while (a_pos > 0) {
--c_pos;
if (a->frac[--a_pos] < borrow) {
c->frac[c_pos] = BASE + a->frac[a_pos] - borrow;
borrow = 1;
}
else {
c->frac[c_pos] = a->frac[a_pos] - borrow;
borrow = 0;
}
}
if (c_pos) c->frac[c_pos - 1] -= borrow;
goto Exit;
Assign_a:
VpAsgn(c, a, 1);
mrv = 0;
Exit:
#ifdef BIGDECIMAL_DEBUG
if (gfDebug) {
VPrint(stdout, "VpSubAbs exit: c=% \n", c);
}
#endif /* BIGDECIMAL_DEBUG */
return mrv;
}
/*
* Note: If(av+bv)>= HALF_BASE,then 1 will be added to the least significant
* digit of c(In case of addition).
* ------------------------- figure of output -----------------------------------
* a = xxxxxxxxxxx
* b = xxxxxxxxxx
* c =xxxxxxxxxxxxxxx
* word_shift = | |
* right_word = | | (Total digits in RHSV)
* left_word = | | (Total digits in LHSV)
* a_pos = |
* b_pos = |
* c_pos = |
*/
static size_t
VpSetPTR(Real *a, Real *b, Real *c, size_t *a_pos, size_t *b_pos, size_t *c_pos, DECDIG *av, DECDIG *bv)
{
size_t left_word, right_word, word_shift;
size_t const round_limit = (VpGetPrecLimit() + BASE_FIG - 1) / BASE_FIG;
assert(a->exponent >= b->exponent);
c->frac[0] = 0;
*av = *bv = 0;
word_shift = (a->exponent - b->exponent);
left_word = b->Prec + word_shift;
right_word = Max(a->Prec, left_word);
left_word = c->MaxPrec - 1; /* -1 ... prepare for round up */
/*
* check if 'round' is needed.
*/
if (right_word > left_word) { /* round ? */
/*---------------------------------
* Actual size of a = xxxxxxAxx
* Actual size of b = xxxBxxxxx
* Max. size of c = xxxxxx
* Round off = |-----|
* c_pos = |
* right_word = |
* a_pos = |
*/
*c_pos = right_word = left_word + 1; /* Set resulting precision */
/* be equal to that of c */
if (a->Prec >= c->MaxPrec) {
/*
* a = xxxxxxAxxx
* c = xxxxxx
* a_pos = |
*/
*a_pos = left_word;
if (*a_pos <= round_limit) {
*av = a->frac[*a_pos]; /* av is 'A' shown in above. */
}
}
else {
/*
* a = xxxxxxx
* c = xxxxxxxxxx
* a_pos = |
*/
*a_pos = a->Prec;
}
if (b->Prec + word_shift >= c->MaxPrec) {
/*
* a = xxxxxxxxx
* b = xxxxxxxBxxx
* c = xxxxxxxxxxx
* b_pos = |
*/
if (c->MaxPrec >= word_shift + 1) {
*b_pos = c->MaxPrec - word_shift - 1;
if (*b_pos + word_shift <= round_limit) {
*bv = b->frac[*b_pos];
}
}
else {
*b_pos = -1L;
}
}
else {
/*
* a = xxxxxxxxxxxxxxxx
* b = xxxxxx
* c = xxxxxxxxxxxxx
* b_pos = |
*/
*b_pos = b->Prec;
}
}
else { /* The MaxPrec of c - 1 > The Prec of a + b */
/*
* a = xxxxxxx
* b = xxxxxx
* c = xxxxxxxxxxx
* c_pos = |
*/
*b_pos = b->Prec;
*a_pos = a->Prec;
*c_pos = right_word + 1;
}
c->Prec = *c_pos;
c->exponent = a->exponent;
if (!AddExponent(c, 1)) return (size_t)-1L;
return word_shift;
}
/*
* Return number of significant digits
* c = a * b , Where a = a0a1a2 ... an
* b = b0b1b2 ... bm
* c = c0c1c2 ... cl
* a0 a1 ... an * bm
* a0 a1 ... an * bm-1
* . . .
* . . .
* a0 a1 .... an * b0
* +_____________________________
* c0 c1 c2 ...... cl
* nc <---|
* MaxAB |--------------------|
*/
VP_EXPORT size_t
VpMult(Real *c, Real *a, Real *b)
{
size_t MxIndA, MxIndB, MxIndAB, MxIndC;
size_t ind_c, i, ii, nc;
size_t ind_as, ind_ae, ind_bs;
DECDIG carry;
DECDIG_DBL s;
Real *w;
#ifdef BIGDECIMAL_DEBUG
if (gfDebug) {
VPrint(stdout, "VpMult(Enter): a=% \n", a);
VPrint(stdout, " b=% \n", b);
}
#endif /* BIGDECIMAL_DEBUG */
if (!VpIsDefOP(c, a, b, OP_SW_MULT)) return 0; /* No significant digit */
if (VpIsZero(a) || VpIsZero(b)) {
/* at least a or b is zero */
VpSetZero(c, VpGetSign(a) * VpGetSign(b));
return 1; /* 0: 1 significant digit */
}
if (VpIsOne(a)) {
VpAsgn(c, b, VpGetSign(a));
goto Exit;
}
if (VpIsOne(b)) {
VpAsgn(c, a, VpGetSign(b));
goto Exit;
}
if (b->Prec > a->Prec) {
/* Adjust so that digits(a)>digits(b) */
w = a;
a = b;
b = w;
}
w = NULL;
MxIndA = a->Prec - 1;
MxIndB = b->Prec - 1;
MxIndC = c->MaxPrec - 1;
MxIndAB = a->Prec + b->Prec - 1;
if (MxIndC < MxIndAB) { /* The Max. prec. of c < Prec(a)+Prec(b) */
w = c;
c = VpAlloc((size_t)((MxIndAB + 1) * BASE_FIG), "#0", 1, 1);
MxIndC = MxIndAB;
}
/* set LHSV c info */
c->exponent = a->exponent; /* set exponent */
if (!AddExponent(c, b->exponent)) {
if (w) VpFree(c);
return 0;
}
VpSetSign(c, VpGetSign(a) * VpGetSign(b)); /* set sign */
carry = 0;
nc = ind_c = MxIndAB;
memset(c->frac, 0, (nc + 1) * sizeof(DECDIG)); /* Initialize c */
c->Prec = nc + 1; /* set precision */
for (nc = 0; nc < MxIndAB; ++nc, --ind_c) {
if (nc < MxIndB) { /* The left triangle of the Fig. */
ind_as = MxIndA - nc;
ind_ae = MxIndA;
ind_bs = MxIndB;
}
else if (nc <= MxIndA) { /* The middle rectangular of the Fig. */
ind_as = MxIndA - nc;
ind_ae = MxIndA - (nc - MxIndB);
ind_bs = MxIndB;
}
else /* if (nc > MxIndA) */ { /* The right triangle of the Fig. */
ind_as = 0;
ind_ae = MxIndAB - nc - 1;
ind_bs = MxIndB - (nc - MxIndA);
}
for (i = ind_as; i <= ind_ae; ++i) {
s = (DECDIG_DBL)a->frac[i] * b->frac[ind_bs--];
carry = (DECDIG)(s / BASE);
s -= (DECDIG_DBL)carry * BASE;
c->frac[ind_c] += (DECDIG)s;
if (c->frac[ind_c] >= BASE) {
s = c->frac[ind_c] / BASE;
carry += (DECDIG)s;
c->frac[ind_c] -= (DECDIG)(s * BASE);
}
if (carry) {
ii = ind_c;
while (ii-- > 0) {
c->frac[ii] += carry;
if (c->frac[ii] >= BASE) {
carry = c->frac[ii] / BASE;
c->frac[ii] -= (carry * BASE);
}
else {
break;
}
}
}
}
}
if (w != NULL) { /* free work variable */
VpNmlz(c);
VpAsgn(w, c, 1);
VpFree(c);
c = w;
}
else {
VpLimitRound(c,0);
}
Exit:
#ifdef BIGDECIMAL_DEBUG
if (gfDebug) {
VPrint(stdout, "VpMult(c=a*b): c=% \n", c);
VPrint(stdout, " a=% \n", a);
VPrint(stdout, " b=% \n", b);
}
#endif /*BIGDECIMAL_DEBUG */
return c->Prec*BASE_FIG;
}
/*
* c = a / b, remainder = r
*/
VP_EXPORT size_t
VpDivd(Real *c, Real *r, Real *a, Real *b)
{
size_t word_a, word_b, word_c, word_r;
size_t i, n, ind_a, ind_b, ind_c, ind_r;
size_t nLoop;
DECDIG_DBL q, b1, b1p1, b1b2, b1b2p1, r1r2;
DECDIG borrow, borrow1, borrow2;
DECDIG_DBL qb;
#ifdef BIGDECIMAL_DEBUG
if (gfDebug) {
VPrint(stdout, " VpDivd(c=a/b) a=% \n", a);
VPrint(stdout, " b=% \n", b);
}
#endif /*BIGDECIMAL_DEBUG */
VpSetNaN(r);
if (!VpIsDefOP(c, a, b, OP_SW_DIV)) goto Exit;
if (VpIsZero(a) && VpIsZero(b)) {
VpSetNaN(c);
return VpException(VP_EXCEPTION_NaN, "Computation results to 'NaN'", 0);
}
if (VpIsZero(b)) {
VpSetInf(c, VpGetSign(a) * VpGetSign(b));
return VpException(VP_EXCEPTION_ZERODIVIDE, "Divide by zero", 0);
}
if (VpIsZero(a)) {
/* numerator a is zero */
VpSetZero(c, VpGetSign(a) * VpGetSign(b));
VpSetZero(r, VpGetSign(a) * VpGetSign(b));
goto Exit;
}
if (VpIsOne(b)) {
/* divide by one */
VpAsgn(c, a, VpGetSign(b));
VpSetZero(r, VpGetSign(a));
goto Exit;
}
word_a = a->Prec;
word_b = b->Prec;
word_c = c->MaxPrec;
word_r = r->MaxPrec;
if (word_a >= word_r) goto space_error;
ind_r = 1;
r->frac[0] = 0;
while (ind_r <= word_a) {
r->frac[ind_r] = a->frac[ind_r - 1];
++ind_r;
}
while (ind_r < word_r) r->frac[ind_r++] = 0;
ind_c = 0;
while (ind_c < word_c) c->frac[ind_c++] = 0;
/* initial procedure */
b1 = b1p1 = b->frac[0];
if (b->Prec <= 1) {
b1b2p1 = b1b2 = b1p1 * BASE;
}
else {
b1p1 = b1 + 1;
b1b2p1 = b1b2 = b1 * BASE + b->frac[1];
if (b->Prec > 2) ++b1b2p1;
}
/* */
/* loop start */
ind_c = word_r - 1;
nLoop = Min(word_c,ind_c);
ind_c = 1;
while (ind_c < nLoop) {
if (r->frac[ind_c] == 0) {
++ind_c;
continue;
}
r1r2 = (DECDIG_DBL)r->frac[ind_c] * BASE + r->frac[ind_c + 1];
if (r1r2 == b1b2) {
/* The first two word digits is the same */
ind_b = 2;
ind_a = ind_c + 2;
while (ind_b < word_b) {
if (r->frac[ind_a] < b->frac[ind_b]) goto div_b1p1;
if (r->frac[ind_a] > b->frac[ind_b]) break;
++ind_a;
++ind_b;
}
/* The first few word digits of r and b is the same and */
/* the first different word digit of w is greater than that */
/* of b, so quotient is 1 and just subtract b from r. */
borrow = 0; /* quotient=1, then just r-b */
ind_b = b->Prec - 1;
ind_r = ind_c + ind_b;
if (ind_r >= word_r) goto space_error;
n = ind_b;
for (i = 0; i <= n; ++i) {
if (r->frac[ind_r] < b->frac[ind_b] + borrow) {
r->frac[ind_r] += (BASE - (b->frac[ind_b] + borrow));
borrow = 1;
}
else {
r->frac[ind_r] = r->frac[ind_r] - b->frac[ind_b] - borrow;
borrow = 0;
}
--ind_r;
--ind_b;
}
++c->frac[ind_c];
goto carry;
}
/* The first two word digits is not the same, */
/* then compare magnitude, and divide actually. */
if (r1r2 >= b1b2p1) {
q = r1r2 / b1b2p1; /* q == (DECDIG)q */
c->frac[ind_c] += (DECDIG)q;
ind_r = b->Prec + ind_c - 1;
goto sub_mult;
}
div_b1p1:
if (ind_c + 1 >= word_c) goto out_side;
q = r1r2 / b1p1; /* q == (DECDIG)q */
c->frac[ind_c + 1] += (DECDIG)q;
ind_r = b->Prec + ind_c;
sub_mult:
borrow1 = borrow2 = 0;
ind_b = word_b - 1;
if (ind_r >= word_r) goto space_error;
n = ind_b;
for (i = 0; i <= n; ++i) {
/* now, perform r = r - q * b */
qb = q * b->frac[ind_b];
if (qb < BASE) borrow1 = 0;
else {
borrow1 = (DECDIG)(qb / BASE);
qb -= (DECDIG_DBL)borrow1 * BASE; /* get qb < BASE */
}
if(r->frac[ind_r] < qb) {
r->frac[ind_r] += (DECDIG)(BASE - qb);
borrow2 = borrow2 + borrow1 + 1;
}
else {
r->frac[ind_r] -= (DECDIG)qb;
borrow2 += borrow1;
}
if (borrow2) {
if(r->frac[ind_r - 1] < borrow2) {
r->frac[ind_r - 1] += (BASE - borrow2);
borrow2 = 1;
}
else {
r->frac[ind_r - 1] -= borrow2;
borrow2 = 0;
}
}
--ind_r;
--ind_b;
}
r->frac[ind_r] -= borrow2;
carry:
ind_r = ind_c;
while (c->frac[ind_r] >= BASE) {
c->frac[ind_r] -= BASE;
--ind_r;
++c->frac[ind_r];
}
}
/* End of operation, now final arrangement */
out_side:
c->Prec = word_c;
c->exponent = a->exponent;
if (!AddExponent(c, 2)) return 0;
if (!AddExponent(c, -(b->exponent))) return 0;
VpSetSign(c, VpGetSign(a) * VpGetSign(b));
VpNmlz(c); /* normalize c */
r->Prec = word_r;
r->exponent = a->exponent;
if (!AddExponent(r, 1)) return 0;
VpSetSign(r, VpGetSign(a));
VpNmlz(r); /* normalize r(remainder) */
goto Exit;
space_error:
#ifdef BIGDECIMAL_DEBUG
if (gfDebug) {
printf(" word_a=%"PRIuSIZE"\n", word_a);
printf(" word_b=%"PRIuSIZE"\n", word_b);
printf(" word_c=%"PRIuSIZE"\n", word_c);
printf(" word_r=%"PRIuSIZE"\n", word_r);
printf(" ind_r =%"PRIuSIZE"\n", ind_r);
}
#endif /* BIGDECIMAL_DEBUG */
rb_bug("ERROR(VpDivd): space for remainder too small.");
Exit:
#ifdef BIGDECIMAL_DEBUG
if (gfDebug) {
VPrint(stdout, " VpDivd(c=a/b), c=% \n", c);
VPrint(stdout, " r=% \n", r);
}
#endif /* BIGDECIMAL_DEBUG */
return c->Prec * BASE_FIG;
}
/*
* Input a = 00000xxxxxxxx En(5 preceding zeros)
* Output a = xxxxxxxx En-5
*/
static int
VpNmlz(Real *a)
{
size_t ind_a, i;
if (!VpIsDef(a)) goto NoVal;
if (VpIsZero(a)) goto NoVal;
ind_a = a->Prec;
while (ind_a--) {
if (a->frac[ind_a]) {
a->Prec = ind_a + 1;
i = 0;
while (a->frac[i] == 0) ++i; /* skip the first few zeros */
if (i) {
a->Prec -= i;
if (!AddExponent(a, -(SIGNED_VALUE)i)) return 0;
memmove(&a->frac[0], &a->frac[i], a->Prec*sizeof(DECDIG));
}
return 1;
}
}
/* a is zero(no non-zero digit) */
VpSetZero(a, VpGetSign(a));
return 0;
NoVal:
a->frac[0] = 0;
a->Prec = 1;
return 0;
}
/*
* VpComp = 0 ... if a=b,
* Pos ... a>b,
* Neg ... a<b.
* 999 ... result undefined(NaN)
*/
VP_EXPORT int
VpComp(Real *a, Real *b)
{
int val;
size_t mx, ind;
int e;
val = 0;
if (VpIsNaN(a) || VpIsNaN(b)) return 999;
if (!VpIsDef(a)) {
if (!VpIsDef(b)) e = a->sign - b->sign;
else e = a->sign;
if (e > 0) return 1;
else if (e < 0) return -1;
else return 0;
}
if (!VpIsDef(b)) {
e = -b->sign;
if (e > 0) return 1;
else return -1;
}
/* Zero check */
if (VpIsZero(a)) {
if (VpIsZero(b)) return 0; /* both zero */
val = -VpGetSign(b);
goto Exit;
}
if (VpIsZero(b)) {
val = VpGetSign(a);
goto Exit;
}
/* compare sign */
if (VpGetSign(a) > VpGetSign(b)) {
val = 1; /* a>b */
goto Exit;
}
if (VpGetSign(a) < VpGetSign(b)) {
val = -1; /* a<b */
goto Exit;
}
/* a and b have same sign, && sign!=0,then compare exponent */
if (a->exponent > b->exponent) {
val = VpGetSign(a);
goto Exit;
}
if (a->exponent < b->exponent) {
val = -VpGetSign(b);
goto Exit;
}
/* a and b have same exponent, then compare their significand. */
mx = (a->Prec < b->Prec) ? a->Prec : b->Prec;
ind = 0;
while (ind < mx) {
if (a->frac[ind] > b->frac[ind]) {
val = VpGetSign(a);
goto Exit;
}
if (a->frac[ind] < b->frac[ind]) {
val = -VpGetSign(b);
goto Exit;
}
++ind;
}
if (a->Prec > b->Prec) {
val = VpGetSign(a);
}
else if (a->Prec < b->Prec) {
val = -VpGetSign(b);
}
Exit:
if (val > 1) val = 1;
else if (val < -1) val = -1;
#ifdef BIGDECIMAL_DEBUG
if (gfDebug) {
VPrint(stdout, " VpComp a=%\n", a);
VPrint(stdout, " b=%\n", b);
printf(" ans=%d\n", val);
}
#endif /* BIGDECIMAL_DEBUG */
return (int)val;
}
/*
* cntl_chr ... ASCIIZ Character, print control characters
* Available control codes:
* % ... VP variable. To print '%', use '%%'.
* \n ... new line
* \b ... backspace
* \t ... tab
* Note: % must not appear more than once
* a ... VP variable to be printed
*/
#ifdef BIGDECIMAL_ENABLE_VPRINT
static int
VPrint(FILE *fp, const char *cntl_chr, Real *a)
{
size_t i, j, nc, nd, ZeroSup, sep = 10;
DECDIG m, e, nn;
j = 0;
nd = nc = 0; /* nd : number of digits in fraction part(every 10 digits, */
/* nd<=10). */
/* nc : number of characters printed */
ZeroSup = 1; /* Flag not to print the leading zeros as 0.00xxxxEnn */
while (*(cntl_chr + j)) {
if (*(cntl_chr + j) == '%' && *(cntl_chr + j + 1) != '%') {
nc = 0;
if (VpIsNaN(a)) {
fprintf(fp, SZ_NaN);
nc += 8;
}
else if (VpIsPosInf(a)) {
fprintf(fp, SZ_INF);
nc += 8;
}
else if (VpIsNegInf(a)) {
fprintf(fp, SZ_NINF);
nc += 9;
}
else if (!VpIsZero(a)) {
if (BIGDECIMAL_NEGATIVE_P(a)) {
fprintf(fp, "-");
++nc;
}
nc += fprintf(fp, "0.");
switch (*(cntl_chr + j + 1)) {
default:
break;
case '0': case 'z':
ZeroSup = 0;
++j;
sep = cntl_chr[j] == 'z' ? BIGDECIMAL_COMPONENT_FIGURES : 10;
break;
}
for (i = 0; i < a->Prec; ++i) {
m = BASE1;
e = a->frac[i];
while (m) {
nn = e / m;
if (!ZeroSup || nn) {
nc += fprintf(fp, "%lu", (unsigned long)nn); /* The leading zero(s) */
/* as 0.00xx will not */
/* be printed. */
++nd;
ZeroSup = 0; /* Set to print succeeding zeros */
}
if (nd >= sep) { /* print ' ' after every 10 digits */
nd = 0;
nc += fprintf(fp, " ");
}
e = e - nn * m;
m /= 10;
}
}
nc += fprintf(fp, "E%"PRIdSIZE, VpExponent10(a));
nc += fprintf(fp, " (%"PRIdVALUE", %lu, %lu)", a->exponent, a->Prec, a->MaxPrec);
}
else {
nc += fprintf(fp, "0.0");
}
}
else {
++nc;
if (*(cntl_chr + j) == '\\') {
switch (*(cntl_chr + j + 1)) {
case 'n':
fprintf(fp, "\n");
++j;
break;
case 't':
fprintf(fp, "\t");
++j;
break;
case 'b':
fprintf(fp, "\n");
++j;
break;
default:
fprintf(fp, "%c", *(cntl_chr + j));
break;
}
}
else {
fprintf(fp, "%c", *(cntl_chr + j));
if (*(cntl_chr + j) == '%') ++j;
}
}
j++;
}
return (int)nc;
}
#endif
static void
VpFormatSt(char *psz, size_t fFmt)
{
size_t ie, i, nf = 0;
char ch;
if (fFmt == 0) return;
ie = strlen(psz);
for (i = 0; i < ie; ++i) {
ch = psz[i];
if (!ch) break;
if (ISSPACE(ch) || ch=='-' || ch=='+') continue;
if (ch == '.') { nf = 0; continue; }
if (ch == 'E' || ch == 'e') break;
if (++nf > fFmt) {
memmove(psz + i + 1, psz + i, ie - i + 1);
++ie;
nf = 0;
psz[i] = ' ';
}
}
}
VP_EXPORT ssize_t
VpExponent10(Real *a)
{
ssize_t ex;
size_t n;
if (!VpHasVal(a)) return 0;
ex = a->exponent * (ssize_t)BASE_FIG;
n = BASE1;
while ((a->frac[0] / n) == 0) {
--ex;
n /= 10;
}
return ex;
}
VP_EXPORT void
VpSzMantissa(Real *a,char *psz)
{
size_t i, n, ZeroSup;
DECDIG_DBL m, e, nn;
if (VpIsNaN(a)) {
sprintf(psz, SZ_NaN);
return;
}
if (VpIsPosInf(a)) {
sprintf(psz, SZ_INF);
return;
}
if (VpIsNegInf(a)) {
sprintf(psz, SZ_NINF);
return;
}
ZeroSup = 1; /* Flag not to print the leading zeros as 0.00xxxxEnn */
if (!VpIsZero(a)) {
if (BIGDECIMAL_NEGATIVE_P(a)) *psz++ = '-';
n = a->Prec;
for (i = 0; i < n; ++i) {
m = BASE1;
e = a->frac[i];
while (m) {
nn = e / m;
if (!ZeroSup || nn) {
sprintf(psz, "%lu", (unsigned long)nn); /* The leading zero(s) */
psz += strlen(psz);
/* as 0.00xx will be ignored. */
ZeroSup = 0; /* Set to print succeeding zeros */
}
e = e - nn * m;
m /= 10;
}
}
*psz = 0;
while (psz[-1] == '0') *(--psz) = 0;
}
else {
if (VpIsPosZero(a)) sprintf(psz, "0");
else sprintf(psz, "-0");
}
}
VP_EXPORT int
VpToSpecialString(Real *a,char *psz,int fPlus)
/* fPlus = 0: default, 1: set ' ' before digits, 2: set '+' before digits. */
{
if (VpIsNaN(a)) {
sprintf(psz,SZ_NaN);
return 1;
}
if (VpIsPosInf(a)) {
if (fPlus == 1) {
*psz++ = ' ';
}
else if (fPlus == 2) {
*psz++ = '+';
}
sprintf(psz, SZ_INF);
return 1;
}
if (VpIsNegInf(a)) {
sprintf(psz, SZ_NINF);
return 1;
}
if (VpIsZero(a)) {
if (VpIsPosZero(a)) {
if (fPlus == 1) sprintf(psz, " 0.0");
else if (fPlus == 2) sprintf(psz, "+0.0");
else sprintf(psz, "0.0");
}
else sprintf(psz, "-0.0");
return 1;
}
return 0;
}
VP_EXPORT void
VpToString(Real *a, char *psz, size_t fFmt, int fPlus)
/* fPlus = 0: default, 1: set ' ' before digits, 2: set '+' before digits. */
{
size_t i, n, ZeroSup;
DECDIG shift, m, e, nn;
char *pszSav = psz;
ssize_t ex;
if (VpToSpecialString(a, psz, fPlus)) return;
ZeroSup = 1; /* Flag not to print the leading zeros as 0.00xxxxEnn */
if (BIGDECIMAL_NEGATIVE_P(a)) *psz++ = '-';
else if (fPlus == 1) *psz++ = ' ';
else if (fPlus == 2) *psz++ = '+';
*psz++ = '0';
*psz++ = '.';
n = a->Prec;
for (i = 0; i < n; ++i) {
m = BASE1;
e = a->frac[i];
while (m) {
nn = e / m;
if (!ZeroSup || nn) {
sprintf(psz, "%lu", (unsigned long)nn); /* The reading zero(s) */
psz += strlen(psz);
/* as 0.00xx will be ignored. */
ZeroSup = 0; /* Set to print succeeding zeros */
}
e = e - nn * m;
m /= 10;
}
}
ex = a->exponent * (ssize_t)BASE_FIG;
shift = BASE1;
while (a->frac[0] / shift == 0) {
--ex;
shift /= 10;
}
while (psz[-1] == '0') {
*(--psz) = 0;
}
sprintf(psz, "e%"PRIdSIZE, ex);
if (fFmt) VpFormatSt(pszSav, fFmt);
}
VP_EXPORT void
VpToFString(Real *a, char *psz, size_t fFmt, int fPlus)
/* fPlus = 0: default, 1: set ' ' before digits, 2: set '+' before digits. */
{
size_t i, n;
DECDIG m, e, nn;
char *pszSav = psz;
ssize_t ex;
if (VpToSpecialString(a, psz, fPlus)) return;
if (BIGDECIMAL_NEGATIVE_P(a)) *psz++ = '-';
else if (fPlus == 1) *psz++ = ' ';
else if (fPlus == 2) *psz++ = '+';
n = a->Prec;
ex = a->exponent;
if (ex <= 0) {
*psz++ = '0';*psz++ = '.';
while (ex < 0) {
for (i=0; i < BASE_FIG; ++i) *psz++ = '0';
++ex;
}
ex = -1;
}
for (i = 0; i < n; ++i) {
--ex;
if (i == 0 && ex >= 0) {
sprintf(psz, "%lu", (unsigned long)a->frac[i]);
psz += strlen(psz);
}
else {
m = BASE1;
e = a->frac[i];
while (m) {
nn = e / m;
*psz++ = (char)(nn + '0');
e = e - nn * m;
m /= 10;
}
}
if (ex == 0) *psz++ = '.';
}
while (--ex>=0) {
m = BASE;
while (m /= 10) *psz++ = '0';
if (ex == 0) *psz++ = '.';
}
*psz = 0;
while (psz[-1] == '0') *(--psz) = 0;
if (psz[-1] == '.') sprintf(psz, "0");
if (fFmt) VpFormatSt(pszSav, fFmt);
}
/*
* [Output]
* a[] ... variable to be assigned the value.
* [Input]
* int_chr[] ... integer part(may include '+/-').
* ni ... number of characters in int_chr[],not including '+/-'.
* frac[] ... fraction part.
* nf ... number of characters in frac[].
* exp_chr[] ... exponent part(including '+/-').
* ne ... number of characters in exp_chr[],not including '+/-'.
*/
VP_EXPORT int
VpCtoV(Real *a, const char *int_chr, size_t ni, const char *frac, size_t nf, const char *exp_chr, size_t ne)
{
size_t i, j, ind_a, ma, mi, me;
SIGNED_VALUE e, es, eb, ef;
int sign, signe, exponent_overflow;
/* get exponent part */
e = 0;
ma = a->MaxPrec;
mi = ni;
me = ne;
signe = 1;
exponent_overflow = 0;
memset(a->frac, 0, ma * sizeof(DECDIG));
if (ne > 0) {
i = 0;
if (exp_chr[0] == '-') {
signe = -1;
++i;
++me;
}
else if (exp_chr[0] == '+') {
++i;
++me;
}
while (i < me) {
if (MUL_OVERFLOW_SIGNED_VALUE_P(e, (SIGNED_VALUE)BASE_FIG)) {
es = e;
goto exp_overflow;
}
es = e * (SIGNED_VALUE)BASE_FIG;
if (MUL_OVERFLOW_SIGNED_VALUE_P(e, 10) ||
SIGNED_VALUE_MAX - (exp_chr[i] - '0') < e * 10)
goto exp_overflow;
e = e * 10 + exp_chr[i] - '0';
if (MUL_OVERFLOW_SIGNED_VALUE_P(e, (SIGNED_VALUE)BASE_FIG))
goto exp_overflow;
if (es > (SIGNED_VALUE)(e * BASE_FIG)) {
exp_overflow:
exponent_overflow = 1;
e = es; /* keep sign */
break;
}
++i;
}
}
/* get integer part */
i = 0;
sign = 1;
if (1 /*ni >= 0*/) {
if (int_chr[0] == '-') {
sign = -1;
++i;
++mi;
}
else if (int_chr[0] == '+') {
++i;
++mi;
}
}
e = signe * e; /* e: The value of exponent part. */
e = e + ni; /* set actual exponent size. */
if (e > 0) signe = 1;
else signe = -1;
/* Adjust the exponent so that it is the multiple of BASE_FIG. */
j = 0;
ef = 1;
while (ef) {
if (e >= 0) eb = e;
else eb = -e;
ef = eb / (SIGNED_VALUE)BASE_FIG;
ef = eb - ef * (SIGNED_VALUE)BASE_FIG;
if (ef) {
++j; /* Means to add one more preceding zero */
++e;
}
}
eb = e / (SIGNED_VALUE)BASE_FIG;
if (exponent_overflow) {
int zero = 1;
for ( ; i < mi && zero; i++) zero = int_chr[i] == '0';
for (i = 0; i < nf && zero; i++) zero = frac[i] == '0';
if (!zero && signe > 0) {
VpSetInf(a, sign);
VpException(VP_EXCEPTION_INFINITY, "exponent overflow",0);
}
else VpSetZero(a, sign);
return 1;
}
ind_a = 0;
while (i < mi) {
a->frac[ind_a] = 0;
while (j < BASE_FIG && i < mi) {
a->frac[ind_a] = a->frac[ind_a] * 10 + int_chr[i] - '0';
++j;
++i;
}
if (i < mi) {
++ind_a;
if (ind_a >= ma) goto over_flow;
j = 0;
}
}
/* get fraction part */
i = 0;
while (i < nf) {
while (j < BASE_FIG && i < nf) {
a->frac[ind_a] = a->frac[ind_a] * 10 + frac[i] - '0';
++j;
++i;
}
if (i < nf) {
++ind_a;
if (ind_a >= ma) goto over_flow;
j = 0;
}
}
goto Final;
over_flow:
rb_warn("Conversion from String to BigDecimal overflow (last few digits discarded).");
Final:
if (ind_a >= ma) ind_a = ma - 1;
while (j < BASE_FIG) {
a->frac[ind_a] = a->frac[ind_a] * 10;
++j;
}
a->Prec = ind_a + 1;
a->exponent = eb;
VpSetSign(a, sign);
VpNmlz(a);
return 1;
}
/*
* [Input]
* *m ... Real
* [Output]
* *d ... fraction part of m(d = 0.xxxxxxx). where # of 'x's is fig.
* *e ... exponent of m.
* BIGDECIMAL_DOUBLE_FIGURES ... Number of digits in a double variable.
*
* m -> d*10**e, 0<d<BASE
* [Returns]
* 0 ... Zero
* 1 ... Normal
* 2 ... Infinity
* -1 ... NaN
*/
VP_EXPORT int
VpVtoD(double *d, SIGNED_VALUE *e, Real *m)
{
size_t ind_m, mm, fig;
double div;
int f = 1;
if (VpIsNaN(m)) {
*d = VpGetDoubleNaN();
*e = 0;
f = -1; /* NaN */
goto Exit;
}
else if (VpIsPosZero(m)) {
*d = 0.0;
*e = 0;
f = 0;
goto Exit;
}
else if (VpIsNegZero(m)) {
*d = VpGetDoubleNegZero();
*e = 0;
f = 0;
goto Exit;
}
else if (VpIsPosInf(m)) {
*d = VpGetDoublePosInf();
*e = 0;
f = 2;
goto Exit;
}
else if (VpIsNegInf(m)) {
*d = VpGetDoubleNegInf();
*e = 0;
f = 2;
goto Exit;
}
/* Normal number */
fig = roomof(BIGDECIMAL_DOUBLE_FIGURES, BASE_FIG);
ind_m = 0;
mm = Min(fig, m->Prec);
*d = 0.0;
div = 1.;
while (ind_m < mm) {
div /= (double)BASE;
*d = *d + (double)m->frac[ind_m++] * div;
}
*e = m->exponent * (SIGNED_VALUE)BASE_FIG;
*d *= VpGetSign(m);
Exit:
#ifdef BIGDECIMAL_DEBUG
if (gfDebug) {
VPrint(stdout, " VpVtoD: m=%\n", m);
printf(" d=%e * 10 **%ld\n", *d, *e);
printf(" BIGDECIMAL_DOUBLE_FIGURES = %d\n", BIGDECIMAL_DOUBLE_FIGURES);
}
#endif /*BIGDECIMAL_DEBUG */
return f;
}
/*
* m <- d
*/
VP_EXPORT void
VpDtoV(Real *m, double d)
{
size_t ind_m, mm;
SIGNED_VALUE ne;
DECDIG i;
double val, val2;
if (isnan(d)) {
VpSetNaN(m);
goto Exit;
}
if (isinf(d)) {
if (d > 0.0) VpSetPosInf(m);
else VpSetNegInf(m);
goto Exit;
}
if (d == 0.0) {
VpSetZero(m, 1);
goto Exit;
}
val = (d > 0.) ? d : -d;
ne = 0;
if (val >= 1.0) {
while (val >= 1.0) {
val /= (double)BASE;
++ne;
}
}
else {
val2 = 1.0 / (double)BASE;
while (val < val2) {
val *= (double)BASE;
--ne;
}
}
/* Now val = 0.xxxxx*BASE**ne */
mm = m->MaxPrec;
memset(m->frac, 0, mm * sizeof(DECDIG));
for (ind_m = 0; val > 0.0 && ind_m < mm; ind_m++) {
val *= (double)BASE;
i = (DECDIG)val;
val -= (double)i;
m->frac[ind_m] = i;
}
if (ind_m >= mm) ind_m = mm - 1;
VpSetSign(m, (d > 0.0) ? 1 : -1);
m->Prec = ind_m + 1;
m->exponent = ne;
VpInternalRound(m, 0, (m->Prec > 0) ? m->frac[m->Prec-1] : 0,
(DECDIG)(val*(double)BASE));
Exit:
#ifdef BIGDECIMAL_DEBUG
if (gfDebug) {
printf("VpDtoV d=%30.30e\n", d);
VPrint(stdout, " m=%\n", m);
}
#endif /* BIGDECIMAL_DEBUG */
return;
}
/*
* m <- ival
*/
#if 0 /* unused */
VP_EXPORT void
VpItoV(Real *m, SIGNED_VALUE ival)
{
size_t mm, ind_m;
size_t val, v1, v2, v;
int isign;
SIGNED_VALUE ne;
if (ival == 0) {
VpSetZero(m, 1);
goto Exit;
}
isign = 1;
val = ival;
if (ival < 0) {
isign = -1;
val =(size_t)(-ival);
}
ne = 0;
ind_m = 0;
mm = m->MaxPrec;
while (ind_m < mm) {
m->frac[ind_m] = 0;
++ind_m;
}
ind_m = 0;
while (val > 0) {
if (val) {
v1 = val;
v2 = 1;
while (v1 >= BASE) {
v1 /= BASE;
v2 *= BASE;
}
val = val - v2 * v1;
v = v1;
}
else {
v = 0;
}
m->frac[ind_m] = v;
++ind_m;
++ne;
}
m->Prec = ind_m - 1;
m->exponent = ne;
VpSetSign(m, isign);
VpNmlz(m);
Exit:
#ifdef BIGDECIMAL_DEBUG
if (gfDebug) {
printf(" VpItoV i=%d\n", ival);
VPrint(stdout, " m=%\n", m);
}
#endif /* BIGDECIMAL_DEBUG */
return;
}
#endif
/*
* y = SQRT(x), y*y - x =>0
*/
VP_EXPORT int
VpSqrt(Real *y, Real *x)
{
Real *f = NULL;
Real *r = NULL;
size_t y_prec;
SIGNED_VALUE n, e;
SIGNED_VALUE prec;
ssize_t nr;
double val;
/* Zero or +Infinity ? */
if (VpIsZero(x) || VpIsPosInf(x)) {
VpAsgn(y,x,1);
goto Exit;
}
/* Negative ? */
if (BIGDECIMAL_NEGATIVE_P(x)) {
VpSetNaN(y);
return VpException(VP_EXCEPTION_OP, "sqrt of negative value", 0);
}
/* NaN ? */
if (VpIsNaN(x)) {
VpSetNaN(y);
return VpException(VP_EXCEPTION_OP, "sqrt of 'NaN'(Not a Number)", 0);
}
/* One ? */
if (VpIsOne(x)) {
VpSetOne(y);
goto Exit;
}
n = (SIGNED_VALUE)y->MaxPrec;
if (x->MaxPrec > (size_t)n) n = (ssize_t)x->MaxPrec;
/* allocate temporally variables */
f = VpAlloc(y->MaxPrec * (BASE_FIG + 2), "#1", 1, 1);
r = VpAlloc((n + n) * (BASE_FIG + 2), "#1", 1, 1);
nr = 0;
y_prec = y->MaxPrec;
prec = x->exponent - (ssize_t)y_prec;
if (x->exponent > 0)
++prec;
else
--prec;
VpVtoD(&val, &e, x); /* val <- x */
e /= (SIGNED_VALUE)BASE_FIG;
n = e / 2;
if (e - n * 2 != 0) {
val /= BASE;
n = (e + 1) / 2;
}
VpDtoV(y, sqrt(val)); /* y <- sqrt(val) */
y->exponent += n;
n = (SIGNED_VALUE)roomof(BIGDECIMAL_DOUBLE_FIGURES, BASE_FIG);
y->MaxPrec = Min((size_t)n , y_prec);
f->MaxPrec = y->MaxPrec + 1;
n = (SIGNED_VALUE)(y_prec * BASE_FIG);
if (n < (SIGNED_VALUE)maxnr) n = (SIGNED_VALUE)maxnr;
do {
y->MaxPrec *= 2;
if (y->MaxPrec > y_prec) y->MaxPrec = y_prec;
f->MaxPrec = y->MaxPrec;
VpDivd(f, r, x, y); /* f = x/y */
VpAddSub(r, f, y, -1); /* r = f - y */
VpMult(f, VpPt5, r); /* f = 0.5*r */
if (VpIsZero(f)) goto converge;
VpAddSub(r, f, y, 1); /* r = y + f */
VpAsgn(y, r, 1); /* y = r */
} while (++nr < n);
#ifdef BIGDECIMAL_DEBUG
if (gfDebug) {
printf("ERROR(VpSqrt): did not converge within %ld iterations.\n", nr);
}
#endif /* BIGDECIMAL_DEBUG */
y->MaxPrec = y_prec;
converge:
VpChangeSign(y, 1);
#ifdef BIGDECIMAL_DEBUG
if (gfDebug) {
VpMult(r, y, y);
VpAddSub(f, x, r, -1);
printf("VpSqrt: iterations = %"PRIdSIZE"\n", nr);
VPrint(stdout, " y =% \n", y);
VPrint(stdout, " x =% \n", x);
VPrint(stdout, " x-y*y = % \n", f);
}
#endif /* BIGDECIMAL_DEBUG */
y->MaxPrec = y_prec;
Exit:
VpFree(f);
VpFree(r);
return 1;
}
/*
* Round relatively from the decimal point.
* f: rounding mode
* nf: digit location to round from the decimal point.
*/
VP_EXPORT int
VpMidRound(Real *y, unsigned short f, ssize_t nf)
{
/* fracf: any positive digit under rounding position? */
/* fracf_1further: any positive digits under one further than the rounding position? */
/* exptoadd: number of digits needed to compensate negative nf */
int fracf, fracf_1further;
ssize_t n,i,ix,ioffset, exptoadd;
DECDIG v, shifter;
DECDIG div;
nf += y->exponent * (ssize_t)BASE_FIG;
exptoadd=0;
if (nf < 0) {
/* rounding position too left(large). */
if (f != VP_ROUND_CEIL && f != VP_ROUND_FLOOR) {
VpSetZero(y, VpGetSign(y)); /* truncate everything */
return 0;
}
exptoadd = -nf;
nf = 0;
}
ix = nf / (ssize_t)BASE_FIG;
if ((size_t)ix >= y->Prec) return 0; /* rounding position too right(small). */
v = y->frac[ix];
ioffset = nf - ix*(ssize_t)BASE_FIG;
n = (ssize_t)BASE_FIG - ioffset - 1;
for (shifter = 1, i = 0; i < n; ++i) shifter *= 10;
/* so the representation used (in y->frac) is an array of DECDIG, where
each DECDIG contains a value between 0 and BASE-1, consisting of BASE_FIG
decimal places.
(that numbers of decimal places are typed as ssize_t is somewhat confusing)
nf is now position (in decimal places) of the digit from the start of
the array.
ix is the position (in DECDIGs) of the DECDIG containing the decimal digit,
from the start of the array.
v is the value of this DECDIG
ioffset is the number of extra decimal places along of this decimal digit
within v.
n is the number of decimal digits remaining within v after this decimal digit
shifter is 10**n,
v % shifter are the remaining digits within v
v % (shifter * 10) are the digit together with the remaining digits within v
v / shifter are the digit's predecessors together with the digit
div = v / shifter / 10 is just the digit's precessors
(v / shifter) - div*10 is just the digit, which is what v ends up being reassigned to.
*/
fracf = (v % (shifter * 10) > 0);
fracf_1further = ((v % shifter) > 0);
v /= shifter;
div = v / 10;
v = v - div*10;
/* now v is just the digit required.
now fracf is whether the digit or any of the remaining digits within v are non-zero
now fracf_1further is whether any of the remaining digits within v are non-zero
*/
/* now check all the remaining DECDIGs for zero-ness a whole DECDIG at a time.
if we spot any non-zeroness, that means that we found a positive digit under
rounding position, and we also found a positive digit under one further than
the rounding position, so both searches (to see if any such non-zero digit exists)
can stop */
for (i = ix + 1; (size_t)i < y->Prec; i++) {
if (y->frac[i] % BASE) {
fracf = fracf_1further = 1;
break;
}
}
/* now fracf = does any positive digit exist under the rounding position?
now fracf_1further = does any positive digit exist under one further than the
rounding position?
now v = the first digit under the rounding position */
/* drop digits after pointed digit */
memset(y->frac + ix + 1, 0, (y->Prec - (ix + 1)) * sizeof(DECDIG));
switch (f) {
case VP_ROUND_DOWN: /* Truncate */
break;
case VP_ROUND_UP: /* Roundup */
if (fracf) ++div;
break;
case VP_ROUND_HALF_UP:
if (v>=5) ++div;
break;
case VP_ROUND_HALF_DOWN:
if (v > 5 || (v == 5 && fracf_1further)) ++div;
break;
case VP_ROUND_CEIL:
if (fracf && BIGDECIMAL_POSITIVE_P(y)) ++div;
break;
case VP_ROUND_FLOOR:
if (fracf && BIGDECIMAL_NEGATIVE_P(y)) ++div;
break;
case VP_ROUND_HALF_EVEN: /* Banker's rounding */
if (v > 5) ++div;
else if (v == 5) {
if (fracf_1further) {
++div;
}
else {
if (ioffset == 0) {
/* v is the first decimal digit of its DECDIG;
need to grab the previous DECDIG if present
to check for evenness of the previous decimal
digit (which is same as that of the DECDIG since
base 10 has a factor of 2) */
if (ix && (y->frac[ix-1] % 2)) ++div;
}
else {
if (div % 2) ++div;
}
}
}
break;
}
for (i = 0; i <= n; ++i) div *= 10;
if (div >= BASE) {
if (ix) {
y->frac[ix] = 0;
VpRdup(y, ix);
}
else {
short s = VpGetSign(y);
SIGNED_VALUE e = y->exponent;
VpSetOne(y);
VpSetSign(y, s);
y->exponent = e + 1;
}
}
else {
y->frac[ix] = div;
VpNmlz(y);
}
if (exptoadd > 0) {
y->exponent += (SIGNED_VALUE)(exptoadd / BASE_FIG);
exptoadd %= (ssize_t)BASE_FIG;
for (i = 0; i < exptoadd; i++) {
y->frac[0] *= 10;
if (y->frac[0] >= BASE) {
y->frac[0] /= BASE;
y->exponent++;
}
}
}
return 1;
}
VP_EXPORT int
VpLeftRound(Real *y, unsigned short f, ssize_t nf)
/*
* Round from the left hand side of the digits.
*/
{
DECDIG v;
if (!VpHasVal(y)) return 0; /* Unable to round */
v = y->frac[0];
nf -= VpExponent(y) * (ssize_t)BASE_FIG;
while ((v /= 10) != 0) nf--;
nf += (ssize_t)BASE_FIG-1;
return VpMidRound(y, f, nf);
}
VP_EXPORT int
VpActiveRound(Real *y, Real *x, unsigned short f, ssize_t nf)
{
/* First,assign whole value in truncation mode */
if (VpAsgn(y, x, 10) <= 1) return 0; /* Zero,NaN,or Infinity */
return VpMidRound(y, f, nf);
}
static int
VpLimitRound(Real *c, size_t ixDigit)
{
size_t ix = VpGetPrecLimit();
if (!VpNmlz(c)) return -1;
if (!ix) return 0;
if (!ixDigit) ixDigit = c->Prec-1;
if ((ix + BASE_FIG - 1) / BASE_FIG > ixDigit + 1) return 0;
return VpLeftRound(c, VpGetRoundMode(), (ssize_t)ix);
}
/* If I understand correctly, this is only ever used to round off the final decimal
digit of precision */
static void
VpInternalRound(Real *c, size_t ixDigit, DECDIG vPrev, DECDIG v)
{
int f = 0;
unsigned short const rounding_mode = VpGetRoundMode();
if (VpLimitRound(c, ixDigit)) return;
if (!v) return;
v /= BASE1;
switch (rounding_mode) {
case VP_ROUND_DOWN:
break;
case VP_ROUND_UP:
if (v) f = 1;
break;
case VP_ROUND_HALF_UP:
if (v >= 5) f = 1;
break;
case VP_ROUND_HALF_DOWN:
/* this is ok - because this is the last digit of precision,
the case where v == 5 and some further digits are nonzero
will never occur */
if (v >= 6) f = 1;
break;
case VP_ROUND_CEIL:
if (v && BIGDECIMAL_POSITIVE_P(c)) f = 1;
break;
case VP_ROUND_FLOOR:
if (v && BIGDECIMAL_NEGATIVE_P(c)) f = 1;
break;
case VP_ROUND_HALF_EVEN: /* Banker's rounding */
/* as per VP_ROUND_HALF_DOWN, because this is the last digit of precision,
there is no case to worry about where v == 5 and some further digits are nonzero */
if (v > 5) f = 1;
else if (v == 5 && vPrev % 2) f = 1;
break;
}
if (f) {
VpRdup(c, ixDigit);
VpNmlz(c);
}
}
/*
* Rounds up m(plus one to final digit of m).
*/
static int
VpRdup(Real *m, size_t ind_m)
{
DECDIG carry;
if (!ind_m) ind_m = m->Prec;
carry = 1;
while (carry > 0 && ind_m--) {
m->frac[ind_m] += carry;
if (m->frac[ind_m] >= BASE) m->frac[ind_m] -= BASE;
else carry = 0;
}
if (carry > 0) { /* Overflow,count exponent and set fraction part be 1 */
if (!AddExponent(m, 1)) return 0;
m->Prec = m->frac[0] = 1;
}
else {
VpNmlz(m);
}
return 1;
}
/*
* y = x - fix(x)
*/
VP_EXPORT void
VpFrac(Real *y, Real *x)
{
size_t my, ind_y, ind_x;
if (!VpHasVal(x)) {
VpAsgn(y, x, 1);
goto Exit;
}
if (x->exponent > 0 && (size_t)x->exponent >= x->Prec) {
VpSetZero(y, VpGetSign(x));
goto Exit;
}
else if (x->exponent <= 0) {
VpAsgn(y, x, 1);
goto Exit;
}
/* satisfy: x->exponent > 0 */
y->Prec = x->Prec - (size_t)x->exponent;
y->Prec = Min(y->Prec, y->MaxPrec);
y->exponent = 0;
VpSetSign(y, VpGetSign(x));
ind_y = 0;
my = y->Prec;
ind_x = x->exponent;
while (ind_y < my) {
y->frac[ind_y] = x->frac[ind_x];
++ind_y;
++ind_x;
}
VpNmlz(y);
Exit:
#ifdef BIGDECIMAL_DEBUG
if (gfDebug) {
VPrint(stdout, "VpFrac y=%\n", y);
VPrint(stdout, " x=%\n", x);
}
#endif /* BIGDECIMAL_DEBUG */
return;
}
/*
* y = x ** n
*/
VP_EXPORT int
VpPowerByInt(Real *y, Real *x, SIGNED_VALUE n)
{
size_t s, ss;
ssize_t sign;
Real *w1 = NULL;
Real *w2 = NULL;
if (VpIsZero(x)) {
if (n == 0) {
VpSetOne(y);
goto Exit;
}
sign = VpGetSign(x);
if (n < 0) {
n = -n;
if (sign < 0) sign = (n % 2) ? -1 : 1;
VpSetInf(y, sign);
}
else {
if (sign < 0) sign = (n % 2) ? -1 : 1;
VpSetZero(y,sign);
}
goto Exit;
}
if (VpIsNaN(x)) {
VpSetNaN(y);
goto Exit;
}
if (VpIsInf(x)) {
if (n == 0) {
VpSetOne(y);
goto Exit;
}
if (n > 0) {
VpSetInf(y, (n % 2 == 0 || VpIsPosInf(x)) ? 1 : -1);
goto Exit;
}
VpSetZero(y, (n % 2 == 0 || VpIsPosInf(x)) ? 1 : -1);
goto Exit;
}
if (x->exponent == 1 && x->Prec == 1 && x->frac[0] == 1) {
/* abs(x) = 1 */
VpSetOne(y);
if (BIGDECIMAL_POSITIVE_P(x)) goto Exit;
if ((n % 2) == 0) goto Exit;
VpSetSign(y, -1);
goto Exit;
}
if (n > 0) sign = 1;
else if (n < 0) {
sign = -1;
n = -n;
}
else {
VpSetOne(y);
goto Exit;
}
/* Allocate working variables */
w1 = VpAlloc((y->MaxPrec + 2) * BASE_FIG, "#0", 1, 1);
w2 = VpAlloc((w1->MaxPrec * 2 + 1) * BASE_FIG, "#0", 1, 1);
/* calculation start */
VpAsgn(y, x, 1);
--n;
while (n > 0) {
VpAsgn(w1, x, 1);
s = 1;
while (ss = s, (s += s) <= (size_t)n) {
VpMult(w2, w1, w1);
VpAsgn(w1, w2, 1);
}
n -= (SIGNED_VALUE)ss;
VpMult(w2, y, w1);
VpAsgn(y, w2, 1);
}
if (sign < 0) {
VpDivd(w1, w2, VpConstOne, y);
VpAsgn(y, w1, 1);
}
Exit:
#ifdef BIGDECIMAL_DEBUG
if (gfDebug) {
VPrint(stdout, "VpPowerByInt y=%\n", y);
VPrint(stdout, "VpPowerByInt x=%\n", x);
printf(" n=%"PRIdVALUE"\n", n);
}
#endif /* BIGDECIMAL_DEBUG */
VpFree(w2);
VpFree(w1);
return 1;
}
#ifdef BIGDECIMAL_DEBUG
int
VpVarCheck(Real * v)
/*
* Checks the validity of the Real variable v.
* [Input]
* v ... Real *, variable to be checked.
* [Returns]
* 0 ... correct v.
* other ... error
*/
{
size_t i;
if (v->MaxPrec == 0) {
printf("ERROR(VpVarCheck): Illegal Max. Precision(=%"PRIuSIZE")\n",
v->MaxPrec);
return 1;
}
if (v->Prec == 0 || v->Prec > v->MaxPrec) {
printf("ERROR(VpVarCheck): Illegal Precision(=%"PRIuSIZE")\n", v->Prec);
printf(" Max. Prec.=%"PRIuSIZE"\n", v->MaxPrec);
return 2;
}
for (i = 0; i < v->Prec; ++i) {
if (v->frac[i] >= BASE) {
printf("ERROR(VpVarCheck): Illegal fraction\n");
printf(" Frac[%"PRIuSIZE"]=%"PRIuDECDIG"\n", i, v->frac[i]);
printf(" Prec. =%"PRIuSIZE"\n", v->Prec);
printf(" Exp. =%"PRIdVALUE"\n", v->exponent);
printf(" BASE =%"PRIuDECDIG"\n", BASE);
return 3;
}
}
return 0;
}
#endif /* BIGDECIMAL_DEBUG */
|