-
Notifications
You must be signed in to change notification settings - Fork 23
/
mini-pi_optimized_1_cached_twiddles.cpp
1251 lines (1047 loc) · 34 KB
/
mini-pi_optimized_1_cached_twiddles.cpp
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
/* Mini Pi
*
* Author : Alexander J. Yee
* Date Created : 07/09/2013
* Last Modified : 07/16/2013
*
* This is a miniature program that can compute Pi and e to millions of digits
* in quasi-linear runtime.
*
* This program is very slow since it does almost no optimizations. But it uses
* asymptotically capable algorithms. So it is capable of computing millions of
* digits of Pi - albeit 100x slower than y-cruncher.
*
* The limit of this program is about 800 million digits. Any higher and the
* FFT will encounter malicious round-off error.
*
*
* This branch of the program does the following optimizations:
* - Cached twiddle factors
* - FFT recursion is stopped at 2 points rather than at 1.
*/
// Visual Studio 2010 doesn't have <chrono>.
#if defined(_MSC_VER) && (_MSC_VER <= 1600)
#define USE_CHRONO 0
#else
#define USE_CHRONO 1
#endif
#ifdef _MSC_VER
#pragma warning(disable:4996) // fopen() deprecation
#endif
#define _USE_MATH_DEFINES
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <string>
#include <vector>
#include <complex>
#include <algorithm>
#include <memory>
#include <iostream>
using std::cout;
using std::cerr;
using std::endl;
using std::complex;
#if USE_CHRONO
#include <chrono>
#else
#include <time.h>
#endif
namespace Mini_Pi{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Debug Printing
uint32_t rand_word(){
return (uint32_t)(
(rand() & 0xf) << 0 |
(rand() & 0xf) << 8 |
(rand() & 0xf) << 16 |
(rand() & 0xf) << 24
) % 1000000000;
}
complex<double> rand_complex(){
double r = (double)(rand() % 1000);
double i = (double)(rand() % 1000);
return complex<double>(r, i);
}
void print_fft(complex<double> *T, int k){
int length = 1 << k;
for (int c = 0; c < length; c++){
std::cout << T[c].real() << " + " << T[c].imag() << "i" << " , ";
}
std::cout << std::endl;
}
void print_word(uint32_t word){
char str[] = "012345678";
for (int c = 8; c >= 0; c--){
str[c] = word % 10 + '0';
word /= 10;
}
std::cout << str;
}
void print_words(uint32_t *T, size_t L){
while (L-- > 0){
print_word(T[L]);
}
std::cout << std::endl;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Helpers
double wall_clock(){
// Get the clock in seconds.
#if USE_CHRONO
auto ratio_object = std::chrono::high_resolution_clock::period();
double ratio = (double)ratio_object.num / ratio_object.den;
return std::chrono::high_resolution_clock::now().time_since_epoch().count() * ratio;
#else
return (double)clock() / CLOCKS_PER_SEC;
#endif
}
void dump_to_file(const char *path, const std::string &str){
// Dump a string to a file.
FILE *file = fopen(path, "wb");
if (file == NULL)
throw "Cannot Create File";
fwrite(str.c_str(), 1, str.size(), file);
fclose(file);
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Fast Fourier Transform
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
std::vector<std::vector<complex<double>>> twiddle_table;
void fft_ensure_table(int k){
// Makes sure the twiddle factor table is large enough to handle an FFT of
// size 2^k.
int current_k = (int)twiddle_table.size() - 1;
if (current_k >= k)
return;
// Do one level at a time
if (k - 1 > current_k){
fft_ensure_table(k - 1);
}
size_t length = (size_t)1 << k;
double omega = 2 * M_PI / length;
length /= 2;
// Build the sub-table.
std::vector<complex<double>> sub_table;
for (size_t c = 0; c < length; c++){
// Generate Twiddle Factor
double angle = omega * c;
auto twiddle_factor = complex<double>(cos(angle), sin(angle));
sub_table.push_back(twiddle_factor);
}
// Push into main table.
twiddle_table.push_back(std::move(sub_table));
}
void fft_forward(complex<double> *T, int k){
// Fast Fourier Transform
// This function performs a forward FFT of length 2^k.
// This is a Decimation-in-Frequency (DIF) FFT.
// The frequency domain output is in bit-reversed order.
//Parameters:
// - T - Pointer to array.
// - k - 2^k is the size of the transform
// End recursion at 2 points.
if (k == 1){
complex<double> a = T[0];
complex<double> b = T[1];
T[0] = a + b;
T[1] = a - b;
return;
}
size_t length = (size_t)1 << k;
size_t half_length = length / 2;
// Get local twiddle table.
std::vector<complex<double>> &local_table = twiddle_table[k];
// Perform FFT reduction into two halves.
for (size_t c = 0; c < half_length; c++){
// Grab Twiddle Factor
auto twiddle_factor = local_table[c];
// Grab elements
complex<double> a = T[c];
complex<double> b = T[c + half_length];
// Perform butterfly
T[c ] = a + b;
T[c + half_length] = (a - b) * twiddle_factor;
}
// Recursively perform FFT on lower elements.
fft_forward(T, k - 1);
// Recursively perform FFT on upper elements.
fft_forward(T + half_length, k - 1);
}
void fft_inverse(complex<double> *T, int k){
// Fast Fourier Transform
// This function performs an inverse FFT of length 2^k.
// This is a Decimation-in-Time (DIT) FFT.
// The frequency domain input must be in bit-reversed order.
//Parameters:
// - T - Pointer to array.
// - k - 2^k is the size of the transform
// End recursion at 2 points.
if (k == 1){
complex<double> a = T[0];
complex<double> b = T[1];
T[0] = a + b;
T[1] = a - b;
return;
}
size_t length = (size_t)1 << k;
size_t half_length = length / 2;
// Recursively perform FFT on lower elements.
fft_inverse(T, k - 1);
// Recursively perform FFT on upper elements.
fft_inverse(T + half_length, k - 1);
// Get local twiddle table.
std::vector<complex<double>> &local_table = twiddle_table[k];
// Perform FFT reduction into two halves.
for (size_t c = 0; c < half_length; c++){
// Grab Twiddle Factor
auto twiddle_factor = conj(local_table[c]);
// Grab elements
complex<double> a = T[c];
complex<double> b = T[c + half_length] * twiddle_factor;
// Perform butterfly
T[c ] = a + b;
T[c + half_length] = a - b;
}
}
void fft_pointwise(complex<double> *T, const complex<double> *A, int k){
// Performs pointwise multiplications of two FFT arrays.
//Parameters:
// - T - Pointer to array.
// - k - 2^k is the size of the transform
size_t length = (size_t)1 << k;
for (size_t c = 0; c < length; c++){
T[c] = T[c] * A[c];
}
}
void int_to_fft(complex<double> *T, int k, const uint32_t *A, size_t AL){
// Convert word array into FFT array. Put 3 decimal digits per complex point.
//Parameters:
// - T - FFT array
// - k - 2^k is the size of the transform
// - A - word array
// - AL - length of word array
size_t fft_length = (size_t)1 << k;
complex<double> *Tstop = T + fft_length;
// Since there are 9 digits per word and we want to put 3 digits per
// point, the length of the transform must be at least 3 times the word
// length of the input.
if (fft_length < 3*AL)
throw "FFT length is too small.";
// Convert
for (size_t c = 0; c < AL; c++){
uint32_t word = A[c];
*T++ = word % 1000;
word /= 1000;
*T++ = word % 1000;
word /= 1000;
*T++ = word;
}
// Pad the rest with zeros.
while (T < Tstop)
*T++ = complex<double>(0, 0);
}
void fft_to_int(const complex<double> *T, int k, uint32_t *A, size_t AL){
// Convert FFT array back to word array. Perform rounding and carryout.
//Parameters:
// - T - FFT array
// - A - word array
// - AL - length of word array
// Compute Scaling Factor
size_t fft_length = (size_t)1 << k;
double scale = 1. / fft_length;
// Since there are 9 digits per word and we want to put 3 digits per
// point, the length of the transform must be at least 3 times the word
// length of the input.
if (fft_length < 3*AL)
throw "FFT length is too small.";
// Round and carry out.
uint64_t carry = 0;
for (size_t c = 0; c < AL; c++){
double f_point;
uint64_t i_point;
uint32_t word;
f_point = (*T++).real() * scale; // Load and scale
i_point = (uint64_t)(f_point + 0.5); // Round
carry += i_point; // Add to carry
word = carry % 1000; // Get 3 digits.
carry /= 1000;
f_point = (*T++).real() * scale; // Load and scale
i_point = (uint64_t)(f_point + 0.5); // Round
carry += i_point; // Add to carry
word += (carry % 1000) * 1000; // Get 3 digits.
carry /= 1000;
f_point = (*T++).real() * scale; // Load and scale
i_point = (uint64_t)(f_point + 0.5); // Round
carry += i_point; // Add to carry
word += (carry % 1000) * 1000000; // Get 3 digits.
carry /= 1000;
A[c] = word;
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// BigFloat object
/* This is the big floating-point object. It represents an arbitrary precision
* floating-point number.
*
* Its numerical value is equal to:
*
* word = 10^9
* word^exp * (T[0] + T[1]*word + T[2]*word^2 + ... + T[L - 1]*word^(L - 1))
*
* T is an array of 32-bit integers. Each integer stores 9 decimal digits
* and must always have a value in the range [0, 999999999].
*
* T[L - 1] must never be zero.
*
* The number is positive when (sign = true) and negative when (sign = false).
* Zero is represented as (sign = true) and (L = 0).
*
*/
#define YCL_BIGFLOAT_EXTRA_PRECISION 2
class BigFloat{
public:
BigFloat(BigFloat &&x);
BigFloat& operator=(BigFloat &&x);
BigFloat();
BigFloat(uint32_t x, bool sign = true);
std::string to_string (size_t digits = 0) const;
std::string to_string_sci(size_t digits = 0) const;
size_t get_precision() const;
int64_t get_exponent() const;
uint32_t word_at(int64_t mag) const;
void negate();
BigFloat mul(uint32_t x) const;
BigFloat add(const BigFloat &x, size_t p = 0) const;
BigFloat sub(const BigFloat &x, size_t p = 0) const;
BigFloat mul(const BigFloat &x, size_t p = 0) const;
BigFloat rcp(size_t p) const;
BigFloat div(const BigFloat &x, size_t p) const;
private:
bool sign; // true = positive or zero, false = negative
int64_t exp; // Exponent
size_t L; // Length
std::unique_ptr<uint32_t[]> T;
// Internal helpers
int64_t to_string_trimmed(size_t digits, std::string &str) const;
int ucmp(const BigFloat &x) const;
BigFloat uadd(const BigFloat &x, size_t p) const;
BigFloat usub(const BigFloat &x, size_t p) const;
friend BigFloat invsqrt(uint32_t x, size_t p);
};
BigFloat invsqrt(uint32_t x, size_t p);
////////////////////////////////////////////////////////////////////////////////
// Move operators
BigFloat::BigFloat(BigFloat &&x)
: sign(x.sign)
, exp(x.exp)
, L(x.L)
, T(std::move(x.T))
{
x.sign = true;
x.exp = 0;
x.L = 0;
}
BigFloat& BigFloat::operator=(BigFloat &&x){
sign = x.sign;
exp = x.exp;
L = x.L;
T = std::move(x.T);
x.sign = true;
x.exp = 0;
x.L = 0;
return *this;
}
////////////////////////////////////////////////////////////////////////////////
// Constructors
BigFloat::BigFloat()
: sign(true)
, exp(0)
, L(0)
{}
BigFloat::BigFloat(uint32_t x, bool sign_)
: sign(true)
, exp(0)
, L(1)
{
// Construct a BigFloat with a value of x and the specified sign.
if (x == 0){
L = 0;
return;
}
sign = sign_;
T = std::unique_ptr<uint32_t[]>(new uint32_t[1]);
T[0] = x;
}
////////////////////////////////////////////////////////////////////////////////
// String Conversion
int64_t BigFloat::to_string_trimmed(size_t digits, std::string &str) const{
// Converts this object to a string with "digits" significant figures.
// After calling this function, the following expression is equal to the
// numeric value of this object. (after truncation of precision)
// str + " * 10^" + (return value)
if (L == 0){
str = "0";
return 0;
}
// Collect operands
int64_t exponent = exp;
size_t length = L;
uint32_t *ptr = T.get();
if (digits == 0){
// Use all digits.
digits = length * 9;
}else{
// Truncate precision
size_t words = (digits + 17) / 9;
if (words < length){
size_t chop = length - words;
exponent += chop;
length = words;
ptr += chop;
}
}
exponent *= 9;
// Build string
char buffer[] = "012345678";
str.clear();
size_t c = length;
while (c-- > 0){
uint32_t word = ptr[c];
for (int i = 8; i >= 0; i--){
buffer[i] = word % 10 + '0';
word /= 10;
}
str += buffer;
}
// Count leading zeros
size_t leading_zeros = 0;
while (str[leading_zeros] == '0')
leading_zeros++;
digits += leading_zeros;
// Truncate
if (digits < str.size()){
exponent += str.size() - digits;
str.resize(digits);
}
return exponent;
}
std::string BigFloat::to_string(size_t digits) const{
// Convert this number to a string. Auto-select format type.
if (L == 0)
return "0.";
int64_t mag = exp + L;
// Use scientific notation if out of range.
if (mag > 1 || mag < 0)
return to_string_sci();
// Convert
std::string str;
int64_t exponent = to_string_trimmed(digits, str);
// Less than 1
if (mag == 0){
if (sign)
return std::string("0.") + str;
else
return std::string("-0.") + str;
}
// Get a string with the digits before the decimal place.
std::string before_decimal = std::to_string((long long)T[L - 1]);
// Nothing after the decimal place.
if (exponent >= 0){
if (sign){
return before_decimal + ".";
}else{
return std::string("-") + before_decimal + ".";
}
}
// Get digits after the decimal place.
std::string after_decimal = str.substr((size_t)(str.size() + exponent), (size_t)-exponent);
if (sign){
return before_decimal + "." + after_decimal;
}else{
return std::string("-") + before_decimal + "." + after_decimal;
}
}
std::string BigFloat::to_string_sci(size_t digits) const{
// Convert to string in scientific notation.
if (L == 0)
return "0.";
// Convert
std::string str;
int64_t exponent = to_string_trimmed(digits, str);
// Strip leading zeros.
{
size_t leading_zeros = 0;
while (str[leading_zeros] == '0')
leading_zeros++;
str = &str[leading_zeros];
}
// Insert decimal place
exponent += str.size() - 1;
str = str.substr(0, 1) + "." + &str[1];
// Add exponent
if (exponent != 0){
str += " * 10^";
str += std::to_string(exponent);
}
// Add sign
if (!sign)
str = std::string("-") + str;
return str;
}
////////////////////////////////////////////////////////////////////////////////
// Getters
size_t BigFloat::get_precision() const{
// Returns the precision of the number in words.
// Note that each word is 9 decimal digits.
return L;
}
int64_t BigFloat::get_exponent() const{
// Returns the exponent of the number in words.
// Note that each word is 9 decimal digits.
return exp;
}
uint32_t BigFloat::word_at(int64_t mag) const{
// Returns the word at the mag'th digit place.
// This is useful for additions where you need to access a specific "digit place"
// of the operand without having to worry if it's out-of-bounds.
// This function is mathematically equal to:
// (return value) = floor(this * (10^9)^-mag) % 10^9
if (mag < exp)
return 0;
if (mag >= exp + (int64_t)L)
return 0;
return T[(size_t)(mag - exp)];
}
int BigFloat::ucmp(const BigFloat &x) const{
// Compare function that ignores the sign.
// This is needed to determine which direction subtractions will go.
// Magnitude
int64_t magA = exp + L;
int64_t magB = x.exp + x.L;
if (magA > magB)
return 1;
if (magA < magB)
return -1;
// Compare
int64_t mag = magA;
while (mag >= exp || mag >= x.exp){
uint32_t wordA = word_at(mag);
uint32_t wordB = x.word_at(mag);
if (wordA < wordB)
return -1;
if (wordA > wordB)
return 1;
mag--;
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
// Arithmetic
void BigFloat::negate(){
// Negate this number.
if (L == 0)
return;
sign = !sign;
}
BigFloat BigFloat::mul(uint32_t x) const{
// Multiply by a 32-bit unsigned integer.
if (L == 0 || x == 0)
return BigFloat();
// Compute basic fields.
BigFloat z;
z.sign = sign;
z.exp = exp;
z.L = L;
// Allocate mantissa
z.T = std::unique_ptr<uint32_t[]>(new uint32_t[z.L + 1]);
uint64_t carry = 0;
for (size_t c = 0; c < L; c++){
carry += (uint64_t)T[c] * x; // Multiply and add to carry
z.T[c] = (uint32_t)(carry % 1000000000); // Store bottom 9 digits
carry /= 1000000000; // Shift down the carry
}
// Carry out
if (carry != 0)
z.T[z.L++] = (uint32_t)carry;
return z;
}
BigFloat BigFloat::uadd(const BigFloat &x, size_t p) const{
// Perform addition ignoring the sign of the two operands.
// Magnitude
int64_t magA = exp + L;
int64_t magB = x.exp + x.L;
int64_t top = std::max(magA, magB);
int64_t bot = std::min(exp, x.exp);
// Target length
int64_t TL = top - bot;
if (p == 0){
// Default value. No trunction.
p = (size_t)TL;
}else{
// Increase precision
p += YCL_BIGFLOAT_EXTRA_PRECISION;
}
// Perform precision truncation.
if (TL > (int64_t)p){
bot = top - p;
TL = p;
}
// Compute basic fields.
BigFloat z;
z.sign = sign;
z.exp = bot;
z.L = (uint32_t)TL;
// Allocate mantissa
z.T = std::unique_ptr<uint32_t[]>(new uint32_t[z.L + 1]);
// Add
uint32_t carry = 0;
for (size_t c = 0; bot < top; bot++, c++){
uint32_t word = word_at(bot) + x.word_at(bot) + carry;
carry = 0;
if (word >= 1000000000){
word -= 1000000000;
carry = 1;
}
z.T[c] = word;
}
// Carry out
if (carry != 0){
z.T[z.L++] = 1;
}
return z;
}
BigFloat BigFloat::usub(const BigFloat &x, size_t p) const{
// Perform subtraction ignoring the sign of the two operands.
// "this" must be greater than or equal to x. Otherwise, the behavior
// is undefined.
// Magnitude
int64_t magA = exp + L;
int64_t magB = x.exp + x.L;
int64_t top = std::max(magA, magB);
int64_t bot = std::min(exp, x.exp);
// Truncate precision
int64_t TL = top - bot;
if (p == 0){
// Default value. No trunction.
p = (size_t)TL;
}else{
// Increase precision
p += YCL_BIGFLOAT_EXTRA_PRECISION;
}
if (TL > (int64_t)p){
bot = top - p;
TL = p;
}
// Compute basic fields.
BigFloat z;
z.sign = sign;
z.exp = bot;
z.L = (uint32_t)TL;
// Allocate mantissa
z.T = std::unique_ptr<uint32_t[]>(new uint32_t[z.L]);
// Subtract
int32_t carry = 0;
for (size_t c = 0; bot < top; bot++, c++){
int32_t word = (int32_t)word_at(bot) - (int32_t)x.word_at(bot) - carry;
carry = 0;
if (word < 0){
word += 1000000000;
carry = 1;
}
z.T[c] = word;
}
// Strip leading zeros
while (z.L > 0 && z.T[z.L - 1] == 0)
z.L--;
if (z.L == 0){
z.exp = 0;
z.sign = true;
z.T.reset();
}
return z;
}
BigFloat BigFloat::add(const BigFloat &x, size_t p) const{
// Addition
// The target precision is p.
// If (p = 0), then no truncation is done. The entire operation is done
// at maximum precision with no data loss.
// Same sign. Add.
if (sign == x.sign)
return uadd(x, p);
// this > x
if (ucmp(x) > 0)
return usub(x, p);
// this < x
return x.usub(*this, p);
}
BigFloat BigFloat::sub(const BigFloat &x, size_t p) const{
// Subtraction
// The target precision is p.
// If (p = 0), then no truncation is done. The entire operation is done
// at maximum precision with no data loss.
// Different sign. Add.
if (sign != x.sign)
return uadd(x, p);
// this > x
if (ucmp(x) > 0)
return usub(x, p);
// this < x
BigFloat z = x.usub(*this, p);
z.negate();
return z;
}
BigFloat BigFloat::mul(const BigFloat &x, size_t p) const{
// Multiplication
// The target precision is p.
// If (p = 0), then no truncation is done. The entire operation is done
// at maximum precision with no data loss.
// Either operand is zero.
if (L == 0 || x.L == 0)
return BigFloat();
if (p == 0){
// Default value. No trunction.
p = L + x.L;
}else{
// Increase precision
p += YCL_BIGFLOAT_EXTRA_PRECISION;
}
// Collect operands.
int64_t Aexp = exp;
int64_t Bexp = x.exp;
size_t AL = L;
size_t BL = x.L;
uint32_t *AT = T.get();
uint32_t *BT = x.T.get();
// Perform precision truncation.
if (AL > p){
size_t chop = AL - p;
AL = p;
Aexp += chop;
AT += chop;
}
if (BL > p){
size_t chop = BL - p;
BL = p;
Bexp += chop;
BT += chop;
}
// Compute basic fields.
BigFloat z;
z.sign = sign == x.sign; // Sign is positive if signs are equal.
z.exp = Aexp + Bexp; // Add the exponents.
z.L = AL + BL; // Add the lenghts for now. May need to correct later.
// Allocate mantissa
z.T = std::unique_ptr<uint32_t[]>(new uint32_t[z.L]);
// Perform multiplication.
// Determine minimum FFT size.
int k = 0;
size_t length = 1;
while (length < 3*z.L){
length <<= 1;
k++;
}
// Perform a convolution using FFT.
// Yeah, this is slow for small sizes, but it's asympotically optimal.
// 3 digits per point is small enough to not encounter round-off error
// until a transform size of 2^30.
// A transform length of 2^29 allows for the maximum product size to be
// 2^29 * 3 = 1,610,612,736 decimal digits.
if (k > 29)
throw "FFT size limit exceeded.";
// Allocate FFT arrays
auto Ta = std::unique_ptr<complex<double>[]>(new complex<double>[length]);
auto Tb = std::unique_ptr<complex<double>[]>(new complex<double>[length]);
// Make sure the twiddle table is big enough.
fft_ensure_table(k);
int_to_fft(Ta.get(), k, AT, AL); // Convert 1st operand
int_to_fft(Tb.get(), k, BT, BL); // Convert 2nd operand
fft_forward(Ta.get(), k); // Transform 1st operand
fft_forward(Tb.get(), k); // Transform 2nd operand
fft_pointwise(Ta.get(), Tb.get(), k); // Pointwise multiply
fft_inverse(Ta.get(), k); // Perform inverse transform.
fft_to_int(Ta.get(), k, z.T.get(), z.L); // Convert back to word array.
// Check top word and correct length.
if (z.T[z.L - 1] == 0)
z.L--;
return z;
}
BigFloat BigFloat::rcp(size_t p) const{
// Compute reciprocal using Newton's Method.
// r1 = r0 - (r0 * x - 1) * r0
if (L == 0)
throw "Divide by Zero";
// Collect operand
int64_t Aexp = exp;
size_t AL = L;
uint32_t *AT = T.get();
// End of recursion. Generate starting point.
if (p == 0){
// Truncate precision to 3.
p = 3;
if (AL > p){
size_t chop = AL - p;
AL = p;
Aexp += chop;
AT += chop;
}
// Convert number to floating-point.
double val = AT[0];
if (AL >= 2)
val += AT[1] * 1000000000.;
if (AL >= 3)
val += AT[2] * 1000000000000000000.;
// Compute reciprocal.
val = 1. / val;
Aexp = -Aexp;
// Scale
while (val < 1000000000.){
val *= 1000000000.;
Aexp--;
}
// Rebuild a BigFloat.
uint64_t val64 = (uint64_t)val;
BigFloat out;
out.sign = sign;
out.T = std::unique_ptr<uint32_t[]>(new uint32_t[2]);
out.T[0] = (uint32_t)(val64 % 1000000000);
out.T[1] = (uint32_t)(val64 / 1000000000);
out.L = 2;
out.exp = Aexp;
return out;
}
// Half the precision
size_t s = p / 2 + 1;
if (p == 1) s = 0;
if (p == 2) s = 1;
// Recurse at half the precision
BigFloat T = rcp(s);
// r1 = r0 - (r0 * x - 1) * r0
return T.sub(this->mul(T, p).sub(BigFloat(1), p).mul(T, p), p);
}
BigFloat BigFloat::div(const BigFloat &x, size_t p) const{
// Division
return this->mul(x.rcp(p), p);
}
BigFloat invsqrt(uint32_t x, size_t p){
// Compute inverse square root using Newton's Method.
// ( r0^2 * x - 1 )
// r1 = r0 - (----------------) * r0
// ( 2 )
if (x == 0)
throw "Divide by Zero";
// End of recursion. Generate starting point.
if (p == 0){
double val = 1. / sqrt((double)x);
int64_t exponent = 0;
// Scale
while (val < 1000000000.){
val *= 1000000000.;