/
Quad.cs
2711 lines (2325 loc) · 119 KB
/
Quad.cs
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
/*
Copyright (c) 2011 Jeff Pasternack. All rights reserved.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Text;
namespace BreakInfinity.Benchmarks.Quadruple
{
/// <summary>
/// Quad is a signed 128-bit floating point number, stored internally as a 64-bit significand (with the most significant bit as the sign bit) and
/// a 64-bit signed exponent, with a value == significand * 2^exponent. Quads have both a higher precision (64 vs. 53 effective significand bits)
/// and a much higher range (64 vs. 11 exponent bits) than doubles, but also support NaN and PositiveInfinity/NegativeInfinity values and can be generally
/// used as a drop-in replacement for doubles, much like double is a drop-in replacement for float. Operations are checked and become +/- infinity in the
/// event of overflow (values larger than ~8E+2776511644261678592) and 0 in the event of underflow (values less than ~4E-2776511644261678592).
/// </summary>
/// <remarks>
/// <para>
/// Exponents >= long.MaxValue - 64 and exponents <= long.MinValue + 64 are reserved
/// and constitute overflow and underflow, respectively. Zero, PositiveInfinity, NegativeInfinity and NaN are
/// defined by significand bits == 0 and an exponent of long.MinValue + 0, + 1, + 2, and + 3, respectively.
/// </para>
/// <para>
/// Quad multiplication and division operators are slightly imprecise for the sake of efficiency; specifically,
/// they may assign the wrong least significant bit, such that the precision is effectively only 63 bits rather than 64.
/// </para>
/// <para>
/// For speed, consider using instance methods (like Multiply and Add) rather
/// than the operators (like * and +) when possible, as the former are significantly faster (by as much as 50%).
/// </para>
/// </remarks>
[System.Diagnostics.DebuggerDisplay("{ToString(),nq}")] //this attributes makes the debugger display the value without braces or quotes
public struct Quad
{
#region Public constants
/// <summary>
/// 0. Equivalent to (Quad)0.
/// </summary>
public static readonly Quad Zero = new Quad(0UL, long.MinValue); //there is only one zero; all other significands with exponent long.MinValue are invalid.
/// <summary>
/// 1. Equivalent to (Quad)1.
/// </summary>
public static readonly Quad One = (Quad)1UL; //used for increment/decrement operators
/// <summary>
/// Positive infinity. Equivalent to (Quad)double.PositiveInfinity.
/// </summary>
public static readonly Quad PositiveInfinity = new Quad(0UL, infinityExponent);
/// <summary>
/// Negative infinity. Equivalent to (Quad)double.NegativeInfinity.
/// </summary>
public static readonly Quad NegativeInfinity = new Quad(0UL, negativeInfinityExponent);
/// <summary>
/// The Not-A-Number value. Equivalent to (Quad)double.NaN.
/// </summary>
public static readonly Quad NaN = new Quad(0UL, notANumberExponent);
/// <summary>
/// The maximum value representable by a Quad, (2 - 1/(2^63)) * 2^(long.MaxValue-65)
/// </summary>
public static readonly Quad MaxValue = new Quad(~highestBit, exponentUpperBound);
/// <summary>
/// The minimum value representable by a Quad, -(2 - 1/(2^63)) * 2^(long.MaxValue-65)
/// </summary>
public static readonly Quad MinValue = new Quad(ulong.MaxValue, exponentUpperBound);
/// <summary>
/// The smallest positive value greater than zero representable by a Quad, 2^(long.MinValue+65)
/// </summary>
public static readonly Quad Epsilon = new Quad(0UL, exponentLowerBound);
/// <summary>
/// all the markers for an exponential number, for string parsing
/// </summary>
public static string[] ExponentialMarkers = new string[] { " e+", " E+", "E+", "e+", " e", " E", "E" };
/// <summary>
/// saves creating a new Quad every time we want to compare a quad to this constant
/// </summary>
public static Quad QuadDoubleMin = double.MinValue;
/// <summary>
/// saves creating a new Quad every time we want to compare a quad to this constant
/// </summary>
public static Quad QuadDoubleMax = double.MaxValue;
//above this threshold Quad.ToString() is used instead of NumberFormatting custom class
// < double.Max as numbers close to max fail to get non-infinite values from RoundToSignificantDigits()
public static Quad ThresholdForFormatting = new Quad(double.MaxValue / 10);
#endregion
#region Public fields
/// <summary>
/// The first (most significant) bit of the significand is the sign bit; 0 for positive values, 1 for negative.
/// The remainder of the bits represent the fractional part (after the binary point) of the significant; there is always an implicit "1"
/// preceding the binary point, just as in IEEE's double specification. For "special" values 0, PositiveInfinity, NegativeInfinity, and NaN,
/// SignificantBits == 0.
/// </summary>
public ulong SignificandBits;
/// <summary>
/// The value of the Quad == (-1)^[first bit of significant] * 1.[last 63 bits of significand] * 2^exponent.
/// Exponents >= long.MaxValue - 64 and exponents <= long.MinValue + 64 are reserved.
/// Exponents of long.MinValue + 0, + 1, + 2 and + 3 are used to represent 0, PositiveInfinity, NegativeInfinity, and NaN, respectively.
/// </summary>
public long Exponent;
#endregion
#region Constructors
public Quad(int value)
{
this = value;
}
public Quad(double value)
{
this = value;
}
/// <summary>
/// Creates a new Quad with the given significand bits and exponent. The significand has a first (most significant) bit
/// corresponding to the quad's sign (1 for positive, 0 for negative), and the rest of the bits correspond to the fractional
/// part of the significand value (immediately after the binary point). A "1" before the binary point is always implied.
/// </summary>
/// <param name="significand"></param>
/// <param name="exponent"></param>
public Quad(ulong significandBits, long exponent)
{
SignificandBits = significandBits;
Exponent = exponent;
}
/// <summary>
/// Creates a new Quad with the given significand value and exponent.
/// </summary>
/// <param name="significand"></param>
/// <param name="exponent"></param>
public Quad(long significand, long exponent)
{
if (significand == 0) //handle 0
{
SignificandBits = 0;
Exponent = long.MinValue;
return;
}
if (significand < 0)
{
if (significand == long.MinValue) //corner case
{
SignificandBits = highestBit;
Exponent = 0;
return;
}
significand = -significand;
SignificandBits = highestBit;
}
else
SignificandBits = 0;
int shift = nlz((ulong)significand); //we must normalize the value such that the most significant bit is 1
SignificandBits |= ~highestBit & (((ulong)significand) << shift); //mask out the highest bit--it's implicit
Exponent = exponent - shift;
}
#endregion
#region Helper functions and constants
#region "Special" arithmetic tables for zeros, infinities, and NaN's
//first index = first argument to the operation; second index = second argument
//One's are used as placeholders when dividing a finite by a finite; these will not be used as the actual result of division, of course.
//arguments are in the order: 0, positive infinity, negative infinity, NaN, positive finite, negative finite
private static readonly Quad[,] specialDivisionTable = new Quad[6, 6]
{
{NaN, Zero, Zero, NaN, Zero, Zero}, // 0 divided by something
{PositiveInfinity, NaN, NaN, NaN, PositiveInfinity, NegativeInfinity}, // +inf divided by something
{NegativeInfinity, NaN, NaN, NaN, NegativeInfinity, PositiveInfinity}, // -inf divided by something
{NaN, NaN, NaN, NaN, NaN, NaN}, // NaN divided by something
{PositiveInfinity, Zero, Zero, NaN, One, One}, //positive finite divided by something
{NegativeInfinity, Zero, Zero, NaN, One, One} //negative finite divided by something
};
private static readonly Quad[,] specialMultiplicationTable = new Quad[6, 6]
{
{Zero, NaN, NaN, NaN, Zero, Zero}, // 0 * something
{NaN, PositiveInfinity, NegativeInfinity, NaN, PositiveInfinity, NegativeInfinity}, // +inf * something
{NaN, NegativeInfinity, PositiveInfinity, NaN, NegativeInfinity, PositiveInfinity}, // -inf * something
{NaN, NaN, NaN, NaN, NaN, NaN}, // NaN * something
{Zero, PositiveInfinity, NegativeInfinity, NaN, One, One}, //positive finite * something
{Zero, NegativeInfinity, PositiveInfinity, NaN, One, One} //negative finite * something
};
private static readonly bool[,] specialGreaterThanTable = new bool[6, 6]
{
{false, false, true, false, false, true}, // 0 > something
{true, false, true, false, true, true}, // +inf > something
{false, false, false, false, false, false}, // -inf > something
{false, false, false, false, false, false}, // NaN > something
{true, false, true, false, false, true}, //positive finite > something
{false, false, true, false, false, false} //negative finite > something
};
private static readonly bool[,] specialGreaterEqualThanTable = new bool[6, 6]
{
{true, false, true, false, false, true}, // 0 >= something
{true, true, true, false, true, true}, // +inf >= something
{false, false, true, false, false, false}, // -inf >= something
{false, false, false, false, false, false}, // NaN >= something
{true, false, true, false, false, true}, //positive finite >= something
{false, false, true, false, false, false} //negative finite >= something
};
private static readonly bool[,] specialLessThanTable = new bool[6, 6]
{
{false, true, false, false, true, false}, // 0 < something
{false, false, false, false, false, false}, // +inf < something
{true, true, false, false, true, true}, // -inf < something
{false, false, false, false, false, false}, // NaN < something
{false, true, false, false, false, false}, //positive finite < something
{true, true, false, false, true, false} //negative finite < something
};
private static readonly bool[,] specialLessEqualThanTable = new bool[6, 6]
{
{true, true, false, false, true, false}, // 0 < something
{false, true, false, false, false, false}, // +inf < something
{true, true, true, false, true, true}, // -inf < something
{false, false, false, false, false, false}, // NaN < something
{false, true, false, false, false, false}, //positive finite < something
{true, true, false, false, true, false} //negative finite < something
};
private static readonly Quad[,] specialSubtractionTable = new Quad[6, 6]
{
{Zero, NegativeInfinity, PositiveInfinity, NaN, One, One}, //0 - something
{PositiveInfinity, NaN, PositiveInfinity, NaN, PositiveInfinity, PositiveInfinity}, //+Infinity - something
{NegativeInfinity, NegativeInfinity, NaN, NaN, NegativeInfinity, NegativeInfinity}, //-Infinity - something
{NaN, NaN, NaN, NaN, NaN, NaN}, //NaN - something
{One, NegativeInfinity, PositiveInfinity, NaN, One, One}, //+finite - something
{One, NegativeInfinity, PositiveInfinity, NaN, One, One} //-finite - something
};
private static readonly Quad[,] specialAdditionTable = new Quad[6, 6]
{
{Zero, PositiveInfinity, NegativeInfinity, NaN, One, One}, //0 + something
{PositiveInfinity, PositiveInfinity, NaN, NaN, PositiveInfinity, PositiveInfinity}, //+Infinity + something
{NegativeInfinity, NaN, NegativeInfinity, NaN, NegativeInfinity, NegativeInfinity}, //-Infinity + something
{NaN, NaN, NaN, NaN, NaN, NaN}, //NaN + something
{One, PositiveInfinity, NegativeInfinity, NaN, One, One}, //+finite + something
{One, PositiveInfinity, NegativeInfinity, NaN, One, One} //-finite + something
};
private static readonly double[] specialDoubleLogTable = new double[] { double.NegativeInfinity, double.PositiveInfinity, double.NaN, double.NaN };
private static readonly string[] specialStringTable = new string[] { "0", "Infinity", "-Infinity", "NaN" };
#endregion
private const long zeroExponent = long.MinValue;
private const long infinityExponent = long.MinValue + 1;
private const long negativeInfinityExponent = long.MinValue + 2;
private const long notANumberExponent = long.MinValue + 3;
private const long exponentUpperBound = long.MaxValue - 65; //no exponent should be higher than this
private const long exponentLowerBound = long.MinValue + 65; //no exponent should be lower than this
private const double base2to10Multiplier = 0.30102999566398119521373889472449; //Math.Log(2) / Math.Log(10);
private const ulong highestBit = 1UL << 63;
private const ulong secondHighestBit = 1UL << 62;
private const ulong lowWordMask = 0xffffffff; //lower 32 bits
private const ulong highWordMask = 0xffffffff00000000; //upper 32 bits
private const ulong b = 4294967296; // Number base (32 bits).
private static readonly Quad e19 = (Quad)10000000000000000000UL;
private static readonly Quad e10 = (Quad)10000000000UL;
private static readonly Quad e5 = (Quad)100000UL;
private static readonly Quad e3 = (Quad)1000UL;
private static readonly Quad e1 = (Quad)10UL;
// private static readonly Quad en19 = One / e19;
// private static readonly Quad en10 = One / e10;
// private static readonly Quad en5 = One / e5;
// private static readonly Quad en3 = One / e3;
// private static readonly Quad en1 = One / e1;
private static readonly Quad en18 = One / (Quad)1000000000000000000UL;
private static readonly Quad en9 = One / (Quad)1000000000UL;
private static readonly Quad en4 = One / (Quad)10000UL;
private static readonly Quad en2 = One / (Quad)100UL;
private static readonly double tenTo100 = Math.Pow(10, 100);
private static readonly double tenTo10 = Math.Pow(10, 10);
/// <summary>
/// Returns the position of the highest set bit, counting from the most significant bit position (position 0).
/// Returns 64 if no bit is set.
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
private static int nlz(ulong x)
{
//Future work: might be faster with a huge, explicit nested if tree, or use of an 256-element per-byte array.
int n;
if (x == 0) return (64);
n = 0;
if (x <= 0x00000000FFFFFFFF)
{
n = n + 32;
x = x << 32;
}
if (x <= 0x0000FFFFFFFFFFFF)
{
n = n + 16;
x = x << 16;
}
if (x <= 0x00FFFFFFFFFFFFFF)
{
n = n + 8;
x = x << 8;
}
if (x <= 0x0FFFFFFFFFFFFFFF)
{
n = n + 4;
x = x << 4;
}
if (x <= 0x3FFFFFFFFFFFFFFF)
{
n = n + 2;
x = x << 2;
}
if (x <= 0x7FFFFFFFFFFFFFFF)
{
n = n + 1;
}
return n;
}
#endregion
#region Struct-modifying instance arithmetic functions
public unsafe void Multiply(double multiplierDouble)
{
Quad multiplier;
#region Parse the double
// Implementation note: the use of goto is generally discouraged,
// but here the idea is to copy-paste the casting call for double -> Quad
// to avoid the expense of an additional function call
// and the use of a single "return" goto target keeps things simple
// Translate the double into sign, exponent and mantissa.
//long bits = BitConverter.DoubleToInt64Bits(value); // doing an unsafe pointer-conversion to get the bits is faster
ulong bits = *((ulong*)&multiplierDouble);
// Note that the shift is sign-extended, hence the test against -1 not 1
long exponent = (((long)bits >> 52) & 0x7ffL);
ulong mantissa = (bits) & 0xfffffffffffffUL;
if (exponent == 0x7ffL)
{
if (mantissa == 0)
{
if (bits >= highestBit) //sign bit set?
multiplier = NegativeInfinity;
else
multiplier = PositiveInfinity;
goto Parsed;
}
else
{
multiplier = NaN;
goto Parsed;
}
}
// Subnormal numbers; exponent is effectively one higher,
// but there's no extra normalisation bit in the mantissa
if (exponent == 0)
{
if (mantissa == 0)
{
multiplier = Zero;
goto Parsed;
}
exponent++;
int firstSetPosition = nlz(mantissa);
mantissa <<= firstSetPosition;
exponent -= firstSetPosition;
}
else
{
mantissa = mantissa << 11;
exponent -= 11;
}
exponent -= 1075;
multiplier.SignificandBits = (highestBit & bits) | mantissa;
multiplier.Exponent = exponent;
Parsed:
#endregion
#region Multiply
if (this.Exponent <= notANumberExponent) //zero/infinity/NaN * something
{
Quad result = specialMultiplicationTable[(int)(this.Exponent - zeroExponent), multiplier.Exponent > notANumberExponent ? (int)(4 + (multiplier.SignificandBits >> 63)) : (int)(multiplier.Exponent - zeroExponent)];
this.SignificandBits = result.SignificandBits;
this.Exponent = result.Exponent;
return;
}
else if (multiplier.Exponent <= notANumberExponent) //finite * zero/infinity/NaN
{
Quad result = specialMultiplicationTable[(int)(4 + (this.SignificandBits >> 63)), (int)(multiplier.Exponent - zeroExponent)];
this.SignificandBits = result.SignificandBits;
this.Exponent = result.Exponent;
return;
}
ulong high1 = (this.SignificandBits | highestBit) >> 32; //de-implicitize the 1
ulong high2 = (multiplier.SignificandBits | highestBit) >> 32;
//because the MSB of both significands is 1, the MSB of the result will also be 1, and the product of low bits on both significands is dropped (and thus we can skip its calculation)
ulong significandBits = high1 * high2 + (((this.SignificandBits & lowWordMask) * high2) >> 32) + ((high1 * (multiplier.SignificandBits & lowWordMask)) >> 32);
long qd2Exponent;
long qd1Exponent = this.Exponent;
if (significandBits < (1UL << 63))
{
this.SignificandBits = ((this.SignificandBits ^ multiplier.SignificandBits) & highestBit) | ((significandBits << 1) & ~highestBit);
qd2Exponent = multiplier.Exponent - 1 + 64;
this.Exponent = this.Exponent + qd2Exponent;
}
else
{
this.SignificandBits = ((this.SignificandBits ^ multiplier.SignificandBits) & highestBit) | (significandBits & ~highestBit);
qd2Exponent = multiplier.Exponent + 64;
this.Exponent = this.Exponent + qd2Exponent;
}
if (qd2Exponent < 0 && this.Exponent > qd1Exponent) //did the exponent get larger after adding something negative?
{
this.SignificandBits = 0;
this.Exponent = zeroExponent;
}
else if (qd2Exponent > 0 && this.Exponent < qd1Exponent) //did the exponent get smaller when it should have gotten larger?
{
this.SignificandBits = 0;
this.Exponent = this.SignificandBits >= highestBit ? negativeInfinityExponent : infinityExponent; //overflow
}
else if (this.Exponent < exponentLowerBound) //check for underflow
{
this.SignificandBits = 0;
this.Exponent = zeroExponent;
}
else if (this.Exponent > exponentUpperBound) //overflow
{
this.SignificandBits = 0;
this.Exponent = this.SignificandBits >= highestBit ? negativeInfinityExponent : infinityExponent; //overflow
}
#endregion
}
public void Multiply(Quad multiplier)
{
if (this.Exponent <= notANumberExponent) //zero/infinity/NaN * something
{
Quad result = specialMultiplicationTable[(int)(this.Exponent - zeroExponent), multiplier.Exponent > notANumberExponent ? (int)(4 + (multiplier.SignificandBits >> 63)) : (int)(multiplier.Exponent - zeroExponent)];
this.SignificandBits = result.SignificandBits;
this.Exponent = result.Exponent;
return;
}
else if (multiplier.Exponent <= notANumberExponent) //finite * zero/infinity/NaN
{
Quad result = specialMultiplicationTable[(int)(4 + (this.SignificandBits >> 63)), (int)(multiplier.Exponent - zeroExponent)];
this.SignificandBits = result.SignificandBits;
this.Exponent = result.Exponent;
return;
}
ulong high1 = (this.SignificandBits | highestBit) >> 32; //de-implicitize the 1
ulong high2 = (multiplier.SignificandBits | highestBit) >> 32;
//because the MSB of both significands is 1, the MSB of the result will also be 1, and the product of low bits on both significands is dropped (and thus we can skip its calculation)
ulong significandBits = high1 * high2 + (((this.SignificandBits & lowWordMask) * high2) >> 32) + ((high1 * (multiplier.SignificandBits & lowWordMask)) >> 32);
long qd2Exponent;
long qd1Exponent = this.Exponent;
if (significandBits < (1UL << 63))
{
this.SignificandBits = ((this.SignificandBits ^ multiplier.SignificandBits) & highestBit) | ((significandBits << 1) & ~highestBit);
qd2Exponent = multiplier.Exponent - 1 + 64;
}
else
{
this.SignificandBits = ((this.SignificandBits ^ multiplier.SignificandBits) & highestBit) | (significandBits & ~highestBit);
qd2Exponent = multiplier.Exponent + 64;
}
this.Exponent = this.Exponent + qd2Exponent;
if (qd2Exponent < 0 && this.Exponent > qd1Exponent) //did the exponent get larger after adding something negative?
{
this.SignificandBits = 0;
this.Exponent = zeroExponent;
}
else if (qd2Exponent > 0 && this.Exponent < qd1Exponent) //did the exponent get smaller when it should have gotten larger?
{
this.SignificandBits = 0;
this.Exponent = this.SignificandBits >= highestBit ? negativeInfinityExponent : infinityExponent; //overflow
}
else if (this.Exponent < exponentLowerBound) //check for underflow
{
this.SignificandBits = 0;
this.Exponent = zeroExponent;
}
else if (this.Exponent > exponentUpperBound) //overflow
{
this.SignificandBits = 0;
this.Exponent = this.SignificandBits >= highestBit ? negativeInfinityExponent : infinityExponent; //overflow
}
#region Multiply with reduced branching (slightly faster?)
//zeros
////if (this.Exponent == long.MinValue)// || multiplier.Exponent == long.MinValue)
////{
//// this.Exponent = long.MinValue;
//// this.Significand = 0;
//// return;
////}
//ulong high1 = (this.Significand | highestBit ) >> 32; //de-implicitize the 1
//ulong high2 = (multiplier.Significand | highestBit) >> 32;
////because the MSB of both significands is 1, the MSB of the result will also be 1, and the product of low bits on both significands is dropped (and thus we can skip its calculation)
//ulong significandBits = high1 * high2 + (((this.Significand & lowWordMask) * high2) >> 32) + ((high1 * (multiplier.Significand & lowWordMask)) >> 32);
//if (significandBits < (1UL << 63)) //first bit clear?
//{
// long zeroMask = ((this.Exponent ^ -this.Exponent) & (multiplier.Exponent ^ -multiplier.Exponent)) >> 63;
// this.Significand = (ulong)zeroMask & ((this.Significand ^ multiplier.Significand) & highestBit) | ((significandBits << 1) & ~highestBit);
// this.Exponent = (zeroMask & (this.Exponent + multiplier.Exponent - 1 + 64)) | (~zeroMask & long.MinValue);
//}
//else
//{
// this.Significand = ((this.Significand ^ multiplier.Significand) & highestBit) | (significandBits & ~highestBit);
// this.Exponent = this.Exponent + multiplier.Exponent + 64;
//}
////long zeroMask = ((isZeroBit1 >> 63) & (isZeroBit2 >> 63));
////this.Significand = (ulong)zeroMask & ((this.Significand ^ multiplier.Significand) & highestBit) | ((significandBits << (int)(1 ^ (significandBits >> 63))) & ~highestBit);
////this.Exponent = (zeroMask & (this.Exponent + multiplier.Exponent - 1 + 64 + (long)(significandBits >> 63))) | (~zeroMask & long.MinValue);
#endregion
}
/// <summary>
/// Multiplies this Quad by a given multiplier, but does not check for underflow or overflow in the result.
/// This is substantially (~20%) faster than the standard Multiply() method.
/// </summary>
/// <param name="multiplier"></param>
public void MultiplyUnchecked(Quad multiplier)
{
if (this.Exponent <= notANumberExponent) //zero/infinity/NaN * something
{
Quad result = specialMultiplicationTable[(int)(this.Exponent - zeroExponent), multiplier.Exponent > notANumberExponent ? (int)(4 + (multiplier.SignificandBits >> 63)) : (int)(multiplier.Exponent - zeroExponent)];
this.SignificandBits = result.SignificandBits;
this.Exponent = result.Exponent;
return;
}
else if (multiplier.Exponent <= notANumberExponent) //finite * zero/infinity/NaN
{
Quad result = specialMultiplicationTable[(int)(4 + (this.SignificandBits >> 63)), (int)(multiplier.Exponent - zeroExponent)];
this.SignificandBits = result.SignificandBits;
this.Exponent = result.Exponent;
return;
}
ulong high1 = (this.SignificandBits | highestBit) >> 32; //de-implicitize the 1
ulong high2 = (multiplier.SignificandBits | highestBit) >> 32;
//because the MSB of both significands is 1, the MSB of the result will also be 1, and the product of low bits on both significands is dropped (and thus we can skip its calculation)
ulong significandBits = high1 * high2 + (((this.SignificandBits & lowWordMask) * high2) >> 32) + ((high1 * (multiplier.SignificandBits & lowWordMask)) >> 32);
long qd2Exponent;
// long qd1Exponent = this.Exponent;
if (significandBits < (1UL << 63))
{
this.SignificandBits = ((this.SignificandBits ^ multiplier.SignificandBits) & highestBit) | ((significandBits << 1) & ~highestBit);
qd2Exponent = multiplier.Exponent - 1 + 64;
this.Exponent = this.Exponent + qd2Exponent;
}
else
{
this.SignificandBits = ((this.SignificandBits ^ multiplier.SignificandBits) & highestBit) | (significandBits & ~highestBit);
qd2Exponent = multiplier.Exponent + 64;
this.Exponent = this.Exponent + qd2Exponent;
}
}
public unsafe void Add(double valueDouble)
{
#region Parse the double
// Implementation note: the use of goto is generally discouraged,
// but here the idea is to copy-paste the casting call for double -> Quad
// to avoid the expense of an additional function call
// and the use of a single "return" goto target keeps things simple
Quad value;
{
// Translate the double into sign, exponent and mantissa.
//long bits = BitConverter.DoubleToInt64Bits(value); // doing an unsafe pointer-conversion to get the bits is faster
ulong bits = *((ulong*)&valueDouble);
// Note that the shift is sign-extended, hence the test against -1 not 1
long exponent = (((long)bits >> 52) & 0x7ffL);
ulong mantissa = (bits) & 0xfffffffffffffUL;
if (exponent == 0x7ffL)
{
if (mantissa == 0)
{
if (bits >= highestBit) //sign bit set?
value = NegativeInfinity;
else
value = PositiveInfinity;
goto Parsed;
}
else
{
value = NaN;
goto Parsed;
}
}
// Subnormal numbers; exponent is effectively one higher,
// but there's no extra normalisation bit in the mantissa
if (exponent == 0)
{
if (mantissa == 0)
{
value = Zero;
goto Parsed;
}
exponent++;
int firstSetPosition = nlz(mantissa);
mantissa <<= firstSetPosition;
exponent -= firstSetPosition;
}
else
{
mantissa = mantissa << 11;
exponent -= 11;
}
exponent -= 1075;
value.SignificandBits = (highestBit & bits) | mantissa;
value.Exponent = exponent;
}
Parsed:
#endregion
#region Addition
{
if (this.Exponent <= notANumberExponent) //zero or infinity or NaN + something
{
if (this.Exponent == zeroExponent)
{
this.SignificandBits = value.SignificandBits;
this.Exponent = value.Exponent;
}
else
{
Quad result = specialAdditionTable[(int)(this.Exponent - zeroExponent), value.Exponent > notANumberExponent ? (int)(4 + (value.SignificandBits >> 63)) : (int)(value.Exponent - zeroExponent)];
this.SignificandBits = result.SignificandBits;
this.Exponent = result.Exponent;
}
return;
}
else if (value.Exponent <= notANumberExponent) //finite + (infinity or NaN)
{
if (value.Exponent != zeroExponent)
{
Quad result = specialAdditionTable[(int)(4 + (this.SignificandBits >> 63)), (int)(value.Exponent - zeroExponent)];
this.SignificandBits = result.SignificandBits;
this.Exponent = result.Exponent;
}
return; //if value == 0, no need to change
}
if ((this.SignificandBits ^ value.SignificandBits) >= highestBit) //this and value have different signs--use subtraction instead
{
Subtract(new Quad(value.SignificandBits ^ highestBit, value.Exponent));
return;
}
if (this.Exponent > value.Exponent)
{
if (this.Exponent >= value.Exponent + 64)
return; //value too small to make a difference
else
{
ulong bits = (this.SignificandBits | highestBit) + ((value.SignificandBits | highestBit) >> (int)(this.Exponent - value.Exponent));
if (bits < highestBit) //this can only happen in an overflow
{
this.SignificandBits = (this.SignificandBits & highestBit) | (bits >> 1);
this.Exponent = this.Exponent + 1;
}
else
{
this.SignificandBits = (this.SignificandBits & highestBit) | (bits & ~highestBit);
//this.Exponent = this.Exponent; //exponent stays the same
}
}
}
else if (this.Exponent < value.Exponent)
{
if (value.Exponent >= this.Exponent + 64)
{
this.SignificandBits = value.SignificandBits; //too small to matter
this.Exponent = value.Exponent;
}
else
{
ulong bits = (value.SignificandBits | highestBit) + ((this.SignificandBits | highestBit) >> (int)(value.Exponent - this.Exponent));
if (bits < highestBit) //this can only happen in an overflow
{
this.SignificandBits = (value.SignificandBits & highestBit) | (bits >> 1);
this.Exponent = value.Exponent + 1;
}
else
{
this.SignificandBits = (value.SignificandBits & highestBit) | (bits & ~highestBit);
this.Exponent = value.Exponent;
}
}
}
else //expDiff == 0
{
//the MSB must have the same sign, so the MSB will become 0, and logical overflow is guaranteed in this situation (so we can shift right and increment the exponent).
this.SignificandBits = ((this.SignificandBits + value.SignificandBits) >> 1) | (this.SignificandBits & highestBit);
this.Exponent = this.Exponent + 1;
}
}
#endregion
}
public void Add(Quad value)
{
#region Addition
if (this.Exponent <= notANumberExponent) //zero or infinity or NaN + something
{
if (this.Exponent == zeroExponent)
{
this.SignificandBits = value.SignificandBits;
this.Exponent = value.Exponent;
}
else
{
Quad result = specialAdditionTable[(int)(this.Exponent - zeroExponent), value.Exponent > notANumberExponent ? (int)(4 + (value.SignificandBits >> 63)) : (int)(value.Exponent - zeroExponent)];
this.SignificandBits = result.SignificandBits;
this.Exponent = result.Exponent;
}
return;
}
else if (value.Exponent <= notANumberExponent) //finite + (infinity or NaN)
{
if (value.Exponent != zeroExponent)
{
Quad result = specialAdditionTable[(int)(4 + (this.SignificandBits >> 63)), (int)(value.Exponent - zeroExponent)];
this.SignificandBits = result.SignificandBits;
this.Exponent = result.Exponent;
}
return; //if value == 0, no need to change
}
if ((this.SignificandBits ^ value.SignificandBits) >= highestBit) //this and value have different signs--use subtraction instead
{
Subtract(new Quad(value.SignificandBits ^ highestBit, value.Exponent));
return;
}
if (this.Exponent > value.Exponent)
{
if (this.Exponent >= value.Exponent + 64)
return; //value too small to make a difference
else
{
ulong bits = (this.SignificandBits | highestBit) + ((value.SignificandBits | highestBit) >> (int)(this.Exponent - value.Exponent));
if (bits < highestBit) //this can only happen in an overflow
{
this.SignificandBits = (this.SignificandBits & highestBit) | (bits >> 1);
this.Exponent = this.Exponent + 1;
}
else
{
this.SignificandBits = (this.SignificandBits & highestBit) | (bits & ~highestBit);
//this.Exponent = this.Exponent; //exponent stays the same
}
}
}
else if (this.Exponent < value.Exponent)
{
if (value.Exponent >= this.Exponent + 64)
{
this.SignificandBits = value.SignificandBits; //too small to matter
this.Exponent = value.Exponent;
}
else
{
ulong bits = (value.SignificandBits | highestBit) + ((this.SignificandBits | highestBit) >> (int)(value.Exponent - this.Exponent));
if (bits < highestBit) //this can only happen in an overflow
{
this.SignificandBits = (value.SignificandBits & highestBit) | (bits >> 1);
this.Exponent = value.Exponent + 1;
}
else
{
this.SignificandBits = (value.SignificandBits & highestBit) | (bits & ~highestBit);
this.Exponent = value.Exponent;
}
}
}
else //expDiff == 0
{
//the MSB must have the same sign, so the MSB will become 0, and logical overflow is guaranteed in this situation (so we can shift right and increment the exponent).
this.SignificandBits = ((this.SignificandBits + value.SignificandBits) >> 1) | (this.SignificandBits & highestBit);
this.Exponent = this.Exponent + 1;
}
#endregion
}
public unsafe void Subtract(double valueDouble)
{
#region Parse the double
// Implementation note: the use of goto is generally discouraged,
// but here the idea is to copy-paste the casting call for double -> Quad
// to avoid the expense of an additional function call
// and the use of a single "return" goto target keeps things simple
Quad value;
{
// Translate the double into sign, exponent and mantissa.
//long bits = BitConverter.DoubleToInt64Bits(value); // doing an unsafe pointer-conversion to get the bits is faster
ulong bits = *((ulong*)&valueDouble);
// Note that the shift is sign-extended, hence the test against -1 not 1
long exponent = (((long)bits >> 52) & 0x7ffL);
ulong mantissa = (bits) & 0xfffffffffffffUL;
if (exponent == 0x7ffL)
{
if (mantissa == 0)
{
if (bits >= highestBit) //sign bit set?
value = NegativeInfinity;
else
value = PositiveInfinity;
goto Parsed;
}
else
{
value = NaN;
goto Parsed;
}
}
// Subnormal numbers; exponent is effectively one higher,
// but there's no extra normalisation bit in the mantissa
if (exponent == 0)
{
if (mantissa == 0)
{
value = Zero;
goto Parsed;
}
exponent++;
int firstSetPosition = nlz(mantissa);
mantissa <<= firstSetPosition;
exponent -= firstSetPosition;
}
else
{
mantissa = mantissa << 11;
exponent -= 11;
}
exponent -= 1075;
value.SignificandBits = (highestBit & bits) | mantissa;
value.Exponent = exponent;
}
Parsed:
#endregion
#region Subtraction
if (this.Exponent <= notANumberExponent) //infinity or NaN - something
{
if (this.Exponent == zeroExponent)
{
this.SignificandBits = value.SignificandBits ^ highestBit; //negate value
this.Exponent = value.Exponent;
}
else
{
Quad result = specialSubtractionTable[(int)(this.Exponent - zeroExponent), value.Exponent > notANumberExponent ? (int)(4 + (value.SignificandBits >> 63)) : (int)(value.Exponent - zeroExponent)];
this.SignificandBits = result.SignificandBits;
this.Exponent = result.Exponent;
}
return;
}
else if (value.Exponent <= notANumberExponent) //finite - (infinity or NaN)
{
if (value.Exponent != zeroExponent)
{
Quad result = specialSubtractionTable[(int)(4 + (this.SignificandBits >> 63)), (int)(value.Exponent - zeroExponent)];
this.SignificandBits = result.SignificandBits;
this.Exponent = result.Exponent;
}
return;
}
if ((this.SignificandBits ^ value.SignificandBits) >= highestBit) //this and value have different signs--use addition instead
{
this.Add(new Quad(value.SignificandBits ^ highestBit, value.Exponent));
return;
}
if (this.Exponent > value.Exponent)
{
if (this.Exponent >= value.Exponent + 64)
return; //value too small to make a difference
else
{
ulong bits = (this.SignificandBits | highestBit) - ((value.SignificandBits | highestBit) >> (int)(this.Exponent - value.Exponent));
//make sure MSB is 1
int highestBitPos = nlz(bits);
this.SignificandBits = ((bits << highestBitPos) & ~highestBit) | (this.SignificandBits & highestBit);
this.Exponent = this.Exponent - highestBitPos;
}