/
BigFloat.cs
4213 lines (3570 loc) · 175 KB
/
BigFloat.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 Ryan Scott White. 2020, 2021, 2022, 2023, 2024
// Released under the MIT License. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sub-license, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// This struct was written by human hand. This may change soon.
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Numerics;
using System.Text;
namespace BigFloatLibrary;
// for notes on zero see "BigFloatZeroNotes.txt"
// Considerations when naming this class
// BigFloat : This would indicate a number with a floating decimal point. This describes this class.
// BigRational: This indicates the faction part stored as an actual fraction (Numerator/Denominator).
// BigDecimal: This indicates processing/storage is base-10. However, this class is base-2 based.
/// <summary>
/// BigFloat stores a BigInteger with a floating decimal point.
/// </summary>
[DebuggerDisplay("{DebuggerDisplay}")]
public readonly partial struct BigFloat : IComparable, IComparable<BigFloat>, IEquatable<BigFloat>
{
/// <summary>
/// ExtraHiddenBits helps with precision by keeping an extra 32 bits. ExtraHiddenBits are a fixed amount of least-signification sub-precise bits.
/// These bits helps guard against some nuisances such as "7" * "9" being 60.
/// </summary>
public const int ExtraHiddenBits = 32; // 0-62, must be even (for sqrt)
/// <summary>
/// Gets the full integer with the hidden bits.
/// </summary>
public readonly BigInteger DataBits { get; }
/// <summary>
/// _size are the number of precision bits. It is equal to "ABS(_int).GetBitLength()". The ABS is for
/// power-of-two negative BigIntegers (-1,-2,-4,-8...) so it is the same whether positive or negative.
/// _size INCLUDES ExtraHiddenBits (the Property Size subtracts out ExtraHiddenBits)
/// _size does not include rounding from ExtraHiddenBits. (11[111...111] (where [111...111] is ExtraHiddenBits) is still 2 bits. So the user will see it as 0b100 with a size of 2.)
/// _size is 0 only when '_int==0'
/// When BigFloat is Zero, the size is zero.
/// </summary>
internal readonly int _size; // { get; init; }
//future: Possible future feature
///// <summary>
///// When positive, it's the number of least significant digits in DataBits that repeat.
///// Example: DataBits:11.001(with _extraPrecOrRepeat = 3) would be 11.001001001001...
///// When negative, it is the number of extra virtual zeros tacked on the end of the internal _int for better precision and accuracy.
///// Example: 11.001(with _extraPrecOrRepeat = -3) would be the same as 11.001000
///// For the above example "000" would not take up any space and is also guaranteed to be all 0 bits.
///// When zero, this feature does not get used. (Default)
///// </summary>
// private readonly int _extraPrecOrRepeat;
/// <summary>
/// The Scale (or -Accuracy) is the amount to left shift (<<) the integer (or right shift the radix point) to get to the desired value.
/// When BigFloat is Zero, scale is the point of least accuracy.
/// note: _scale = Scale-ExtraHiddenBits (or Scale = _scale + ExtraHiddenBits)
/// </summary>
public readonly int Scale { get; init; }
/// <summary>
/// The Size is the precision. It in number of bits required to hold the number.
/// ExtraHiddenBits are subtracted out.
/// </summary>
public readonly int Size => Math.Max(0, _size - ExtraHiddenBits);
/// <summary>
/// The number of data bits. ExtraHiddenBits are counted.
/// </summary>
public readonly int SizeWithHiddenBits => _size;
/// <summary>
/// The resulting binary point position when counting from the most significant bit.
/// Or where the [.]dataBits x 2^exp. Example: 0.11010 x 2^3 = 110.10 [Scale + Size]
/// Examples: 0.11 -> 0; 1.11 -> 1; 10.1 -> 2; .001 = -2
/// </summary>
public int Exponent => Scale + _size - ExtraHiddenBits;
//see BigFloatZeroNotes.txt for notes
//perf: should we keep the shortcut "...&& Scale < 0 &&..."?
/// <summary>
/// Returns true if the internal data bits round to zero.
/// </summary>
public bool IsZero => _size < (ExtraHiddenBits - 2) && (_size + Scale) < ExtraHiddenBits; // && Scale < 0
// What is considered Zero: any dataInt that is LESS then 0:100000000, and also the shift results in a 0:100000000.
//
// IntData Scale Size Sz+Sc Precision Zero
// 1:111111111 << -2 33 31 1 N
// 1:000000000 << -2 33 31 1 N
// 1:000000000 << -1 33 32 1 N
// 1:000000000 << 0 33 33 1 N
// 0:111111111 << -1 32 31 0 N
// 0:100000000 << -1 32 31 0 N
// 0:100000000 << 0 32 32 0 N
// 0:011111111 << -1 31 30 -1 Y
// 0:011111111 << 0 31 31 -1 Y (borderline)
// 0:011111111 << 1 31 32 -1 N
// 0:001111111 << 1 31 32 -2 Y (borderline)
// 0:001111111 << 2 31 33 -2 N
/// <summary>
/// Returns true if there is less than 1 bit of precision. However, a false value does not guarantee that the number are precise.
/// </summary>
public bool OutOfPrecision => _size < ExtraHiddenBits;
/// <summary>
/// Returns the precision of the BigFloat. This is the same as the size of the data bits. The precision can be zero or negative. A negative precision means the number is below the number of bits(HiddenBits) that are deemed precise.
/// </summary>
public int GetPrecision => _size - ExtraHiddenBits;
/// <summary>
/// Returns the accuracy of the BigFloat. The accuracy is equivalent to the opposite of the scale. A negative accuracy means the least significant bit is above the one place. A value of zero is equivalent to an integer. A positive value is the number of accurate decimal places(in binary) the number has.
/// </summary>
public int GetAccuracy => -Scale;
/// <summary>
/// Rounds and returns true if this value is positive. Zero is not considered positive or negative. Only the top bit in ExtraHiddenBits is counted.
/// </summary>
public bool IsPositive => Sign > 0;
/// <summary>
/// Rounds and returns true if this value is negative. Only the top bit in ExtraHiddenBits is counted.
/// </summary>
public bool IsNegative => Sign < 0;
/// <summary>
/// Rounds and returns -1 if negative, 0 if zero, and +1 if positive. Only the top bit in ExtraHiddenBits and top out-of-precision hidden bit are included.
/// </summary>
public int Sign => (_size >= ExtraHiddenBits - 1) ? DataBits.Sign : 0;
/// <summary>
/// Gets the integer part of the BigFloat. No scaling is applied. ExtraHiddenBits are rounded and removed.
/// </summary>
public readonly BigInteger Int => DataIntValueWithRound(DataBits);
public string DebuggerDisplay
{
get
{
string bottom8HexChars = (BigInteger.Abs(DataBits) & ((BigInteger.One << ExtraHiddenBits) - 1)).ToString("X8").PadLeft(8)[^8..];
StringBuilder sb = new(32);
_ = sb.Append($"{ToString(true)}, "); // integer part using ToString()
_ = sb.Append($"{(DataBits.Sign >= 0 ? " " : "-")}0x{BigInteger.Abs(DataBits) >> ExtraHiddenBits:X}:{bottom8HexChars}"); // hex part
_ = sb.Append($"[{Size}+{ExtraHiddenBits}={_size}], {((Scale >= 0) ? "<<" : ">>")} {Math.Abs(Scale)}");
return sb.ToString();
}
}
/// <summary>
/// Prints debug information for the BigFloat to the console.
/// </summary>
/// <param name="varName">Prints an optional name of the variable.</param>
public void DebugPrint(string varName = null)
{
string shift = $"{((Scale >= 0) ? "<<" : ">>")} {Math.Abs(Scale)}";
if (!string.IsNullOrEmpty(varName))
{
Console.WriteLine($"{varName + ":"}");
}
Console.WriteLine($" Debug : {DebuggerDisplay}");
Console.WriteLine($" String : {ToString()}");
//Console.WriteLine($" Int|hex: {_int >> ExtraHiddenBits:X}:{(_int & (uint.MaxValue)).ToString("X")[^8..]}[{Size}] {shift} (Hidden-bits round {(WouldRound() ? "up" : "down")})");
Console.WriteLine($" Int|Hex : {ToStringHexScientific(true, true, false)} (Hidden-bits round {(WouldRound() ? "up" : "down")})");
Console.WriteLine($" |Hex : {ToStringHexScientific(true, true, true)} (two's comp)");
Console.WriteLine($" |Dec : {DataBits >> ExtraHiddenBits}{((double)(DataBits & (((ulong)1 << ExtraHiddenBits) - 1)) / ((ulong)1 << ExtraHiddenBits)).ToString()[1..]} {shift}");
Console.WriteLine($" |Dec : {DataBits >> ExtraHiddenBits}:{DataBits & (((ulong)1 << ExtraHiddenBits) - 1)} {shift}"); // decimal part (e.g. .75)
if (DataBits < 0)
{
Console.WriteLine($" or -{-DataBits >> ExtraHiddenBits:X4}:{(-DataBits & (((ulong)1 << ExtraHiddenBits) - 1)).ToString("X8")[^8..]}");
}
Console.WriteLine($" |_int: {DataBits}");
Console.WriteLine($" Scale : {Scale}");
Console.WriteLine();
}
/// <summary>
/// Returns a Zero with no size/precision.
/// </summary>
public static BigFloat ZeroWithNoPrecision => new(0, 0, 0);
/// <summary>
/// Returns a Zero with a given lower bound of precision. Example: -4 would result of 0.0000(in binary). ExtraHiddenBits will be added.
/// </summary>
/// <param name="pointOfLeastPrecision">The precision can be positive or negative.</param>
public static BigFloat ZeroWithSpecifiedLeastPrecision(int pointOfLeastPrecision)
{
return new(BigInteger.Zero, pointOfLeastPrecision, 0);
}
/// <summary>
/// Returns a '1' with only 1 bit of precision. (1 << ExtraHiddenBits)
/// </summary>
public static BigFloat One => new(BigInteger.One << ExtraHiddenBits, 0, ExtraHiddenBits + 1);
/// <summary>
/// Returns a "1" with additional Accuracy. This is beyond the ExtraHiddenBits.
/// </summary>
/// <param name="precisionInBits">The precision between -32(ExtraHiddenBits) to Int.MaxValue.</param>
public static BigFloat OneWithAccuracy(int precisionInBits)
{
// if the precision is shrunk to a size of zero it cannot contain any data bits
return precisionInBits <= -ExtraHiddenBits
? ZeroWithNoPrecision
: new(BigInteger.One << (ExtraHiddenBits + precisionInBits), -precisionInBits, ExtraHiddenBits + 1 + precisionInBits);
// alternative: throw new ArgumentException("The requested precision would leave not leave any bits.");
}
/// <summary>
/// Returns an integer with additional accuracy. This is beyond the ExtraHiddenBits.
/// </summary>
/// <param name="precisionInBits">The precision between (-ExtraHiddenBits - intVal.BitSize) to Int.MaxValue.</param>
public static BigFloat IntWithAccuracy(BigInteger intVal, int precisionInBits)
{
int intSize = (int)BigInteger.Abs(intVal).GetBitLength();
// if the precision is shrunk to a size of zero it cannot contain any data bits
return precisionInBits < -(ExtraHiddenBits + intSize)
? ZeroWithNoPrecision
: new(intVal << (ExtraHiddenBits + precisionInBits), -precisionInBits, ExtraHiddenBits + intSize + precisionInBits);
// alternative: throw new ArgumentException("The requested precision would leave not leave any bits.");
}
/// <summary>
/// Returns an integer with additional accuracy. This is beyond the ExtraHiddenBits.
/// </summary>
/// <param name="precisionInBits">The precision between (-ExtraHiddenBits - intVal.BitSize) to Int.MaxValue.</param>
public static BigFloat IntWithAccuracy(int intVal, int precisionInBits)
{
int size = int.Log2(int.Abs(intVal)) + 1 + ExtraHiddenBits;
return precisionInBits < -size
? ZeroWithNoPrecision
: new(((BigInteger)intVal) << (ExtraHiddenBits + precisionInBits), -precisionInBits, size + precisionInBits);
}
public static BigFloat NegativeOne => new(BigInteger.MinusOne << ExtraHiddenBits, 0, ExtraHiddenBits + 1);
///////////////////////// INIT / CONVERSION FUNCTIONS /////////////////////////
/// <summary>
/// Contracts a BigFloat using the raw elemental parts. The user is responsible to pre-up-shift rawValue and set <param name="scale"> and <param name="rawValueSize">.
/// </summary>
/// <param name="rawValue">The raw integerPart. It should INCLUDE the ExtraHiddenBits.</param>
/// <param name="rawValueSize">The size of rawValue. </param>
private BigFloat(BigInteger rawValue, int scale, int rawValueSize)
{
DataBits = rawValue;
Scale = scale;
_size = rawValueSize;
AssertValid();
}
/// <summary>
/// Constructs a BigFloat using its elemental parts.
/// </summary>
/// <param name="integerPart">The integer part of the BigFloat that will have a <param name="scale"> applied to it. </param>
/// <param name="scale">How much should the <param name="integerPart"> be shifted or scaled? This shift (base-2 exponent) will be applied to the <param name="integerPart">.</param>
/// <param name="valueIncludesHiddenBits">if true, then the hidden bits should be included in the integer part.</param>
public BigFloat(BigInteger integerPart, int scale = 0, bool valueIncludesHiddenBits = false)
{
int applyHiddenBits = valueIncludesHiddenBits ? 0 : ExtraHiddenBits;
// we need Abs() so items that are a negative power of 2 has the same size as the positive version.
DataBits = integerPart << applyHiddenBits;
_size = (int)BigInteger.Abs(DataBits).GetBitLength();
Scale = scale; // _int of zero can have scale
AssertValid();
}
public BigFloat(char integerPart, int scale = 0)
{
DataBits = (BigInteger)integerPart << ExtraHiddenBits;
Scale = scale;
// Special handing required for int.MinValue
_size = integerPart >= 0
? integerPart == 0 ? 0 : BitOperations.Log2(integerPart) + 1 + ExtraHiddenBits
: integerPart != char.MinValue
? integerPart == 0 ? 0 : BitOperations.Log2((byte)-integerPart) + 1 + ExtraHiddenBits
: 7 + ExtraHiddenBits;
AssertValid();
}
public BigFloat(byte integerPart, int scale = 0)
{
DataBits = (BigInteger)integerPart << ExtraHiddenBits;
Scale = scale;
_size = integerPart == 0 ? 0 : BitOperations.Log2(integerPart) + 1 + ExtraHiddenBits;
AssertValid();
}
public BigFloat(int integerPart, int scale = 0) : this((long)integerPart, scale) { }
public BigFloat(uint value, int scale = 0)
{
DataBits = (BigInteger)value << ExtraHiddenBits;
Scale = scale;
_size = value == 0 ? 0 : BitOperations.Log2(value) + 1 + ExtraHiddenBits;
AssertValid();
}
public BigFloat(long value, int scale = 0)
{
DataBits = (BigInteger)value << ExtraHiddenBits;
Scale = scale;
_size = value switch
{
> 0 => BitOperations.Log2((ulong)value) + 1 + ExtraHiddenBits,
< 0 => 64 - BitOperations.LeadingZeroCount(~((ulong)value - 1)) + ExtraHiddenBits,
_ => 0,
};
AssertValid();
}
public BigFloat(ulong value, int scale = 0)
{
DataBits = (BigInteger)value << ExtraHiddenBits;
Scale = scale;
_size = value == 0 ? 0 : BitOperations.Log2(value) + 1 + ExtraHiddenBits;
AssertValid();
}
public BigFloat(Int128 integerPart, int scale = 0)
{
DataBits = (BigInteger)integerPart << ExtraHiddenBits;
Scale = scale;
_size = integerPart > Int128.Zero
? (int)Int128.Log2(integerPart) + 1 + ExtraHiddenBits
: integerPart < Int128.Zero ? 128 - (int)Int128.LeadingZeroCount(~(integerPart - 1)) + ExtraHiddenBits : 0;
AssertValid();
}
public BigFloat(Int128 integerPart, int scale, bool valueIncludesHiddenBits)
{
DataBits = (BigInteger)integerPart << ExtraHiddenBits;
Scale = scale;
_size = integerPart > Int128.Zero
? (int)Int128.Log2(integerPart) + 1 + ExtraHiddenBits
: integerPart < Int128.Zero ? 128 - (int)Int128.LeadingZeroCount(~(integerPart - 1)) + ExtraHiddenBits : 0;
AssertValid();
int applyHiddenBits = valueIncludesHiddenBits ? 0 : ExtraHiddenBits;
// we need Abs() so items that are a negative power of 2 has the same size as the positive version.
_size = (int)((BigInteger)(integerPart >= 0 ? integerPart : -integerPart)).GetBitLength() + applyHiddenBits;
DataBits = integerPart << applyHiddenBits;
Scale = scale; // _int of zero can have scale
AssertValid();
}
public BigFloat(double value, int additionalScale = 0)
{
long bits = BitConverter.DoubleToInt64Bits(value);
long mantissa = bits & 0xfffffffffffffL;
int exp = (int)((bits >> 52) & 0x7ffL);
if (exp == 2047) // 2047 represents inf or NAN
{
//if (double.IsNaN(value))
//{
// _int = 0;
// Scale = scale;
// _size = 0;
// return;
//}
//if (double.IsInfinity(value))
//{
// ThrowInitializeException();
//}
ThrowInitializeException(); // mantissa==0 is Inf else NAN
}
else if (exp != 0)
{
mantissa |= 0x10000000000000L;
if (value < 0)
{
mantissa = -mantissa;
}
DataBits = new BigInteger(mantissa) << ExtraHiddenBits;
Scale = exp - 1023 - 52 + additionalScale;
_size = 53 + ExtraHiddenBits; //_size = BitOperations.Log2((ulong)Int);
}
else // exp is 0 so this is a denormalized float (leading "1" is "0" instead)
{
// 0:00000000000:00...0001 -> smallest value (Epsilon) Int:1, Scale: Size:1
// ...
if (mantissa == 0)
{
DataBits = 0;
Scale = additionalScale;
_size = 0;
}
else
{
int size = 64 - BitOperations.LeadingZeroCount((ulong)mantissa);
if (value < 0)
{
mantissa = -mantissa;
}
DataBits = (new BigInteger(mantissa)) << (ExtraHiddenBits);
Scale = -1023 - 52 + 1 + additionalScale;
_size = size + ExtraHiddenBits;
}
}
AssertValid();
}
public BigFloat(float value, int additionalScale = 0)
{
int bits = BitConverter.SingleToInt32Bits(value);
int mantissa = bits & 0x007fffff;
int exp = (int)((bits >> 23) & 0xffL);
if (exp != 0)
{
if (exp == 255)
{ //special values
//if (float.IsNaN(value))
//{
// _int = 0;
// Scale = scale;
// _size = 0;
// return;
//}
//if (float.IsInfinity(value))
//{
// ThrowInitializeException();
//}
ThrowInitializeException(); // mantissa==0 is Inf else NAN
}
// Add leading 1 bit
mantissa |= 0x800000;
if (value < 0)
{
mantissa = -mantissa;
}
DataBits = new BigInteger(mantissa) << ExtraHiddenBits;
Scale = exp - 127 - 23 + additionalScale;
_size = 24 + ExtraHiddenBits;
}
else // exp is 0 so this is a denormalized(Subnormal) float (leading "1" is "0" instead)
{
if (mantissa == 0)
{
DataBits = 0;
Scale = additionalScale;
_size = 0; //24 + ExtraHiddenBits;
}
else
{
BigInteger mant = new(value >= 0 ? mantissa : -mantissa);
DataBits = mant << ExtraHiddenBits;
Scale = -126 - 23 + additionalScale; //hack: 23 is a guess
_size = 32 - BitOperations.LeadingZeroCount((uint)mantissa) + ExtraHiddenBits;
}
}
AssertValid();
}
[DoesNotReturn]
private static void ThrowInitializeException()
{
throw new OverflowException("Value was too large for a BigFloat.");
}
/// <summary>
/// Parses an input string and returns a BigFloat. If it fails, an exception is thrown.
/// This function supports:
/// - Positive or negative leading signs or no sign.
/// - Radix point (aka. decimal point for base 10)
/// - Hex strings starting with a [-,+,_]0x (radix point and sign supported)
/// - Binary strings starting with a [-,+,_]0b (radix point and sign supported)
/// </summary>
/// <param name="numericString">The input decimal/hex/binary number.</param>
/// <param name="additionalScale">Optional apply positive or negative base-2 scaling.(default is zero)</param>
public BigFloat(string value, int additionalScale = 0)
{
this = Parse(value, additionalScale);
}
///////////////////////// [END] INIT / CONVERSION FUNCTIONS [END] /////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////// TO_STRING FUNCTIONS ////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
// see "BigFloatToStringNotes.txt" and "BigFloatTryParseNotes.txt" for additional notes
// string ToString() - calls ToStringDecimal()
// string ToString(string format) - to Hex(e.g. A4B.F2) and Binary(e.g. 1010111.001)
// string ToStringDecimal() - To Decimal, e.g. 9999.99
// string ToStringHexScientific(bool showHiddenBits = false, bool showSize = false, bool showInTwosComplement = false) - e.g. "12AC<<22"
[DebuggerHidden()]
public override string ToString()
{
return ToStringDecimal(this, false);
}
[DebuggerHidden()]
public string ToString(bool includeOutOfPrecisionBits = false)
{
return ToStringDecimal(this, includeOutOfPrecisionBits);
}
/// <summary>
/// Format the value of the current instance to a decimal number.
/// </summary>
/// <param name="val">The BigFloat that should be converted to a string.</param>
/// <param name="includeOutOfPrecisionBits">Include out-of-precision bits in result. This will include additional decimal places.</param>
//[DebuggerHidden()]
public static string ToStringDecimal(BigFloat val, bool includeOutOfPrecisionBits = false)
{
BigInteger intVal = val.DataBits;
int scale = val.Scale;
int valSize = val._size;
if (scale < -1) // Number will have a decimal point. (e.g. 222.22, 0.01, 3.1)
// -1 is not enough to form a full decimal digit.
{
if (includeOutOfPrecisionBits)
{
intVal <<= ExtraHiddenBits;
scale -= ExtraHiddenBits;
valSize += ExtraHiddenBits;
}
int exponent = scale + valSize - ExtraHiddenBits;
// How many digits do we need? (does not need to be exact at this stage)
int digitsNeeded = (int)Math.Round(-scale / 3.32192809488736235);
//int digitsNeeded = (int)(-Scale2 / 3.32192809488736235) + 1;
BigInteger power5 = BigInteger.Abs(intVal) * BigInteger.Pow(5, digitsNeeded);
// Applies the scale to the number and rounds from bottom bit
BigInteger power5Scaled = RightShiftWithRound(power5, -scale - digitsNeeded + ExtraHiddenBits);
// If zero, then special handling required. Add as many precision zeros based on scale.
if (power5Scaled.IsZero)
{
if (RightShiftWithRound(intVal, ExtraHiddenBits).IsZero)
{
return $"0.{new string('0', digitsNeeded)}";
}
// solves an issue when with a "BigFloat(1, -8)" being 0.000
digitsNeeded++;
power5 = BigInteger.Abs(intVal) * BigInteger.Pow(5, digitsNeeded);
power5Scaled = RightShiftWithRound(power5, -scale - digitsNeeded + ExtraHiddenBits);
}
string numberText = power5Scaled.ToString();
int decimalOffset = numberText.Length - digitsNeeded;
//int decimalOffset2 = ((int)((_size - ExtraHiddenBits + scale2) / 3.32192809488736235)) - ((numberText[0] - '5') / 8.0); //alternative
// The length should have room for [-][digits][.][digits]
int length = (intVal < 0 ? 3 : 2) + numberText.Length - (exponent <= 0 ? decimalOffset : 1);
char[] chars = new char[length];
int position = 0;
if (intVal < 0)
{
chars[position++] = '-';
}
// We can round a 0.99 to a 1.00, hence the "(Exponent==0 && decimalOffset <= 0)"
if (exponent < 0 || (exponent == 0 && decimalOffset <= 0)) // 0.xxxxx
{
chars[position++] = '0';
chars[position++] = '.';
for (int i = decimalOffset; i < 0; i++)
{
chars[position++] = '0';
}
numberText.CopyTo(0, chars, position, numberText.Length);
return new string(chars);
}
else // xxxx.xxxx
{
numberText.CopyTo(0, chars, position, decimalOffset);
position += decimalOffset;
chars[position++] = '.';
numberText.CopyTo(decimalOffset, chars, position, numberText.Length - decimalOffset);
return new string(chars);
}
}
else // XXXXX or 7XXXXX (The numbers with no decimal precision.) (scale >= 0)
{
if (includeOutOfPrecisionBits)
{
// returns integer WITHOUT hidden bits masked.
return RightShiftWithRound(intVal, ExtraHiddenBits - scale).ToString();
}
//int maskSize = (int)((scale + 2.86313809) / 3.32192809488736235); // this number was test for a large range of floats
int maskSize = (int)((scale + 3.18507) / 3.32192809488736235); // 3.18507 was tested for a wide range of floats
BigInteger power5 = (intVal << (scale - maskSize)) / BigInteger.Pow(5, maskSize);
BigInteger power5Scaled = RightShiftWithRound(power5, ExtraHiddenBits); // Applies the scale to the number and rounds from bottom bit
//Console.WriteLine(power5Scaled.ToString() + new string('X', maskSize));
return power5Scaled.ToString()
+ ((maskSize < 10) ? new string('X', maskSize) : " * 10^" + maskSize.ToString());
}
}
/// <summary>
/// Writes a BigFloat in Hex('X') or Binary('B'). A radix point is supported. Negative values must have a leading '-'.
/// </summary>
/// <param name="format">Format specifier: 'X' for hex, 'B' for binary, or empty for decimal.</param>
/// <returns>The value as a string.</returns>
public string ToString(string format)
{
if (string.IsNullOrEmpty(format))
{
return ToString();
}
//// Lets round and remove the ExtraHiddenBits now.
//BigInteger newInt = DataIntValueWithRound(BigInteger.Abs(_int), out bool needToRound);
//int size = (int)newInt.GetBitLength();
//int newScale = Scale;
if (format[0] == 'X') //hex with radix point
{
if (Scale >= 0)
{
//return (newInt >> Scale).ToString("X");
return (DataBits >> (ExtraHiddenBits - Scale)).ToString("X"); // This version includes hidden bits in result
}
// We have to align the INT to the nearest 4 bits for hex. We also want to remove the ExtraHiddenBits.
// The number of bits between the radix point and the end should be divisible by 4. We will dig into the ExtraHiddenBits for this.
int rightShift = (ExtraHiddenBits - Scale) & 0x03;
BigInteger shiftedBigIntForDisplay = RightShiftWithRound(DataBits, rightShift);
return shiftedBigIntForDisplay.ToString("X").Insert((-Scale / 4) - 1, ".");
}
if (format[0] == 'B') // Signals a binary (with radix point)
{
// Setup destination and allocate memory
Span<char> dstBytes = stackalloc char[_size - ExtraHiddenBits
+ Math.Max(Math.Max(Scale, -(_size - ExtraHiddenBits) - Scale), 0) // total number of out-of-precision zeros in the output.
+ (DataBits.Sign < 0 ? 1 : 0) // add one if a leading '-' sign (-0.1)
+ (Scale < 0 ? 1 : 0) // add one if it has a point like (1.1)
+ (Exponent <= 0 ? 1 : 0)]; // add one if <1 for leading Zero (0.1)
int dstIndex = 0;
// Three types
// Type '12300' - if all bits are to the left of the radix point(no radix point required)
// Type '12.30' - has numbers below AND above the point. (e.g. 11.01)
// Type '0.123' - all numbers are to the right of the radix point. (has leading 0.or - 0.)
// Pre-append the leading sign.
if (DataBits.Sign < 0)
{
dstBytes[dstIndex] = '-';
dstIndex++;
}
// Setup source bits to read.
ReadOnlySpan<byte> srcBytes = DataIntValueWithRound(BigInteger.Abs(DataBits)).ToByteArray();
int leadingZeroCount = BitOperations.LeadingZeroCount(srcBytes[^1]) - 24;
if (Exponent <= 0) // For binary numbers less then one. (e.g. 0.001101)
{
int outputZerosBetweenPointAndNumber = Math.Max(0, -(_size - ExtraHiddenBits) - Scale);
dstBytes[dstIndex++] = '0';
dstBytes[dstIndex++] = '.';
// Add the leading zeros
for (int i = 0; i < outputZerosBetweenPointAndNumber; i++)
{
dstBytes[dstIndex++] = '0';
}
WriteValueBits(srcBytes, leadingZeroCount, Size, dstBytes[dstIndex..]);
}
else if (Scale >= 0) // For binary numbers with no radix point. (e.g. 1101)
{
int outputZerosBetweenNumberAndPoint = Math.Max(0, Scale);
dstBytes[^outputZerosBetweenNumberAndPoint..].Fill('0');
WriteValueBits(srcBytes, leadingZeroCount, Size, dstBytes[dstIndex..]);
}
else // For numbers with a radix point in the middle (e.g. 101.1 or 10.01, or 1.00)
{
int outputBitsBeforePoint = _size - ExtraHiddenBits + Scale;
int outputBitsAfterPoint = Math.Max(0, -Scale);
WriteValueBits(srcBytes, leadingZeroCount, outputBitsBeforePoint, dstBytes[dstIndex..]);
dstIndex += outputBitsBeforePoint;
//Write Decimal point
dstBytes[dstIndex++] = '.';
WriteValueBits(srcBytes, leadingZeroCount + outputBitsBeforePoint, outputBitsAfterPoint, dstBytes[dstIndex..]);
}
return new string(dstBytes);
}
// If none of the above formats ('X' or 'B') matched, then fail.
throw new FormatException($"The {format} format string is not supported.");
static void WriteValueBits(ReadOnlySpan<byte> srcBytes, int bitStart, int bitCount, Span<char> dstBytes)
{
int srcLoc = srcBytes.Length - 1;
int dstByte = 0;
int cur = bitStart;
while (cur < bitStart + bitCount)
{
int curSrcByte = srcLoc - (cur >> 3);
int curSrcBit = 7 - (cur & 0x7);
byte b2 = srcBytes[curSrcByte];
dstBytes[dstByte++] = (char)('0' + ((b2 >> curSrcBit) & 1));
cur++;
}
}
}
/// <summary>
/// Generates the data-bits in hex followed by the amount to shift(in decimal). Example: 12AC<<22 or B1>>3
/// </summary>
/// <param name="showHiddenBits">Includes the extra 32 hidden bits. Example: 12AC:F0F00000<<22</param>
/// <param name="showSize">Appends a [##] to the number with it's size in bits. Example: 22AC[14]<<22</param>
/// <param name="showInTwosComplement">When enabled, shows the show result in two's complement form with no leading sign. Example: -5 --> B[3]<<0</param>
public string ToStringHexScientific(bool showHiddenBits = false, bool showSize = false, bool showInTwosComplement = false)
{
StringBuilder sb = new();
BigInteger intVal = DataBits;
if (!showInTwosComplement && DataBits.Sign < 0)
{
_ = sb.Append('-');
intVal = -intVal;
}
_ = sb.Append($"{intVal >> ExtraHiddenBits:X}");
if (showHiddenBits)
{
_ = sb.Append($":{(intVal & (uint.MaxValue)).ToString("X8")[^8..]}");
}
if (showSize)
{
_ = sb.Append($"[{Size}]");
}
_ = sb.Append($" {((Scale >= 0) ? "<<" : ">>")} {Math.Abs(Scale)}");
return sb.ToString();
}
/// <summary>
/// A high performance BigInteger to binary string converter that supports 0 and negative numbers.
/// Negative numbers are returned with a leading '-' sign.
/// </summary>
private static void BigIntegerToBinarySpan(BigInteger x, ref Span<char> dstBytes)
{
bool isNegitive = x.Sign < 0;
if (isNegitive)
{
x = -x;
}
// Setup source
ReadOnlySpan<byte> srcBytes = x.ToByteArray();
int srcLoc = srcBytes.Length - 1;
// Find the first bit set in the first byte so we don't print extra zeros.
int msb = BitOperations.Log2(srcBytes[srcLoc]);
// Setup Target
//Span<char> dstBytes = stackalloc char[srcByte * 8 + MSB + 2];
int dstLoc = 0;
// Add leading '-' sign if negative.
if (isNegitive)
{
dstBytes[dstLoc++] = '-';
}
// The first byte is special because we don't want to print leading zeros.
byte b = srcBytes[srcLoc--];
for (int j = msb; j >= 0; j--)
{
dstBytes[dstLoc++] = (char)('0' + ((b >> j) & 1));
}
// Add the remaining bits.
for (; srcLoc >= 0; srcLoc--)
{
byte b2 = srcBytes[srcLoc];
for (int j = 7; j >= 0; j--)
{
dstBytes[dstLoc++] = (char)('0' + ((b2 >> j) & 1));
}
}
}
/// <summary>
/// A high performance BigInteger to binary string converter that supports 0 and negative numbers.
/// Negative numbers will be returned as two's complement with no sign.
/// The output char[] size will be a multiple of 8.
/// </summary>
private static void BigIntegerToBinarySpanTwosComplement(BigInteger x, ref Span<char> dstBytes)
{
// Setup source
ReadOnlySpan<byte> srcBytes = x.ToByteArray();
int srcLoc = srcBytes.Length - 1;
// Setup Target
int dstLoc = 0;
// Add the remaining bits.
for (; srcLoc >= 0; srcLoc--)
{
byte b2 = srcBytes[srcLoc];
for (int j = 7; j >= 0; j--)
{
dstBytes[dstLoc++] = (char)('0' + ((b2 >> j) & 1));
}
}
}
private static string BigIntegerToBinaryString(BigInteger x, bool twosComplement = false)
{
if (twosComplement)
{
Span<char> charsSpan = stackalloc char[(int)x.GetBitLength() + 7];
//char[] chars = new char[x.GetBitLength() + 2];
//Span<char> charsSpan = new(chars);
BigIntegerToBinarySpanTwosComplement(x, ref charsSpan);
return new string(charsSpan);
}
else
{
Span<char> charsSpan = stackalloc char[(int)x.GetBitLength() + ((x < 0) ? 2 : 1)];
//char[] chars = new char[x.GetBitLength() + ((x < 0) ? 1 : 0)];
//Span<char> charsSpan = new(chars);
BigIntegerToBinarySpan(x, ref charsSpan);
return new string(charsSpan);
}
}
/// <summary>
/// This function returns a specified number of most-significant bits (MSBs) as a char[] array. If the requested number of bits is larger than the data bits, it will be left-shifted and padded with underscores.
/// </summary>
public string GetMostSignificantBits(int numberOfBits)
{
BigInteger abs = BigInteger.Abs(DataBits);
int shiftAmount = _size - numberOfBits;
return shiftAmount >= 0
? BigIntegerToBinaryString(abs >> shiftAmount)
: BigIntegerToBinaryString(abs) + new string('_', -shiftAmount);
}
/// <summary>
/// Returns the value's bits, including hidden bits, as a string.
/// Negative values will have a leading '-' sign.
/// </summary>
public string GetAllBitsAsString(bool twosComplement = false)
{
return BigIntegerToBinaryString(DataBits, twosComplement);
}
/// <summary>
/// Returns the value's bits as a string.
/// Negative values will have a leading '-' sign.
/// </summary>
public string GetBitsAsString()
{
return BigIntegerToBinaryString(Int);
}
/////////////////////////// [END] TO_STRING FUNCTIONS [END] ////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////// PARSE FUNCTIONS FUNCTIONS ////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
// see "BigFloatTryParseNotes.txt" for additional notes
/// <summary>
/// Parses an input string and returns a BigFloat. If it fails, an exception is thrown.
/// This function supports:
/// - Positive or negative leading signs or no sign.
/// - Radix point (aka. decimal point for base 10)
/// - Hex strings starting with a [-,+,_]0x (radix point and sign supported)
/// - Binary strings starting with a [-,+,_]0b (radix point and sign supported)
/// </summary>
/// <param name="numericString">The input decimal/hex/binary number.</param>
/// <param name="scale">Optional apply positive or negative base-2 scaling.(default is zero)</param>
public static BigFloat Parse(string numericString, int scale = 0)
{
bool success = TryParse(numericString, out BigFloat biRes, scale);
if (!success)
{
throw new ArgumentException("Unable to convert string to BigFloat.");
}
biRes.AssertValid();
return biRes;
}
/// <summary>
/// Parses a <param name="numericString"> to a BigFloat.
/// This function supports:
/// - Positive or negative leading signs or no sign.
/// - Radix point (aka. decimal point for base 10)
/// - Hex strings starting with a [-,+,_]0x (radix point and sign supported)
/// - Binary strings starting with a [-,+,_]0b (radix point and sign supported)
/// </summary>
/// <param name="numericString">The input decimal/hex/binary number.</param>
/// <param name="result">The resulting BigFloat. Zero is returned if conversion failed.</param>
/// <param name="scale">Optional apply positive or negative base-2 scaling.(default is zero)</param>
/// <returns>Returns true if successful.</returns>
public static bool TryParse(string numericString, out BigFloat result, int scale = 0)
{
//string orgValue = numericString;
if (string.IsNullOrEmpty(numericString))
{
result = new BigFloat(0);
return false;
}
// Let us check for invalid short strings, 0x___ , or 0b___
{
int locAfterSign = (numericString[0] is '-' or '+') ? 1 : 0;
if (numericString.Length == locAfterSign) //[-,+][END] - fail
{
result = new BigFloat(0);
return false;
}
else if (numericString[locAfterSign] == '0') //[-,+]0___
{
bool isNeg = numericString[0] == '-';
if (numericString.Length > 2 && numericString[locAfterSign + 1] is 'b' or 'B') //[-,+]0b___
{
// remove leading "0x" or "-0x"
return TryParseBinary(numericString.AsSpan(isNeg ? 3 : 2), out result, scale, isNeg ? -1 : 0);
}
else if (numericString.Length > 2 && numericString[locAfterSign + 1] is 'x' or 'X') //[-,+]0x___
{
return TryParseHex(numericString, out result, scale);
}
//else { } // [-,+]0[END] OR [-,+]0___ - continue(exceptions handled by BigInteger.Parse)
}
}
//else if (numericString[1] > '0' && numericString[1] <= '9') { } // [-,+][1-9]__ - continue(exceptions handled by BigInteger.Parse)
//else if (numericString[1] == '.') { } // [-,+].___ - continue(exceptions handled by BigInteger.Parse)
int radixLoc = numericString.IndexOf('.');
// There is a decimal point, so let's remove it to convert it to a BigInteger.
if (radixLoc >= 0)
{
numericString = numericString.Remove(radixLoc, 1);
}
// Check for 'e' like 123e10 or 123.123e+100
int eLoc = numericString.IndexOf('e');
int exp = 0;
if (eLoc > 0)
{
int endOfNub = eLoc;
int begOfExp = eLoc + 1;
int expSign = 1;