-
-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathBigDouble.cs
1309 lines (1086 loc) · 41.1 KB
/
BigDouble.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
using System;
using System.Globalization;
using Random = System.Random;
// I'm not sure if there's a "Yes, this is Unity" define symbol
// (#if UNITY doesn't seem to work). If you happen to know one - please create
// an issue here https://github.com/Razenpok/BreakInfinity.cs/issues.
#if UNITY_2017_1_OR_NEWER
using UnityEngine;
#endif
namespace BreakInfinity
{
#if UNITY_2017_1_OR_NEWER
[Serializable]
#endif
public struct BigDouble : IFormattable, IComparable, IComparable<BigDouble>, IEquatable<BigDouble>
{
public const double Tolerance = 1e-18;
//for example: if two exponents are more than 17 apart, consider adding them together pointless, just return the larger one
private const int MaxSignificantDigits = 17;
private const long ExpLimit = long.MaxValue;
//the largest exponent that can appear in a Double, though not all mantissas are valid here.
private const long DoubleExpMax = 308;
//The smallest exponent that can appear in a Double, though not all mantissas are valid here.
private const long DoubleExpMin = -324;
#if UNITY_2017_1_OR_NEWER
[SerializeField]
private double mantissa;
[SerializeField]
private long exponent;
#else
private double mantissa;
private long exponent;
#endif
// This constructor is used to prevent non-normalized values to be created via constructor.
// ReSharper disable once UnusedParameter.Local
private BigDouble(double mantissa, long exponent, PrivateConstructorArg _)
{
this.mantissa = mantissa;
this.exponent = exponent;
}
public BigDouble(double mantissa, long exponent)
{
this = Normalize(mantissa, exponent);
}
public BigDouble(BigDouble other)
{
mantissa = other.mantissa;
exponent = other.exponent;
}
public BigDouble(double value)
{
//SAFETY: Handle Infinity and NaN in a somewhat meaningful way.
if (double.IsNaN(value))
{
this = NaN;
}
else if (double.IsPositiveInfinity(value))
{
this = PositiveInfinity;
}
else if (double.IsNegativeInfinity(value))
{
this = NegativeInfinity;
}
else if (IsZero(value))
{
this = Zero;
}
else
{
this = Normalize(value, 0);
}
}
public static BigDouble Normalize(double mantissa, long exponent)
{
if (mantissa >= 1 && mantissa < 10 || !IsFinite(mantissa))
{
return FromMantissaExponentNoNormalize(mantissa, exponent);
}
if (IsZero(mantissa))
{
return Zero;
}
var tempExponent = (long)Math.Floor(Math.Log10(Math.Abs(mantissa)));
//SAFETY: handle 5e-324, -5e-324 separately
if (tempExponent == DoubleExpMin)
{
mantissa = mantissa * 10 / 1e-323;
}
else
{
mantissa = mantissa / PowersOf10.Lookup(tempExponent);
}
return FromMantissaExponentNoNormalize(mantissa, exponent + tempExponent);
}
public double Mantissa => mantissa;
public long Exponent => exponent;
public static BigDouble FromMantissaExponentNoNormalize(double mantissa, long exponent)
{
return new BigDouble(mantissa, exponent, new PrivateConstructorArg());
}
public static BigDouble Zero = FromMantissaExponentNoNormalize(0, 0);
public static BigDouble One = FromMantissaExponentNoNormalize(1, 0);
public static BigDouble NaN = FromMantissaExponentNoNormalize(double.NaN, long.MinValue);
public static bool IsNaN(BigDouble value)
{
return double.IsNaN(value.Mantissa);
}
public static BigDouble PositiveInfinity = FromMantissaExponentNoNormalize(double.PositiveInfinity, 0);
public static bool IsPositiveInfinity(BigDouble value)
{
return double.IsPositiveInfinity(value.Mantissa);
}
public static BigDouble NegativeInfinity = FromMantissaExponentNoNormalize(double.NegativeInfinity, 0);
public static bool IsNegativeInfinity(BigDouble value)
{
return double.IsNegativeInfinity(value.Mantissa);
}
public static bool IsInfinity(BigDouble value)
{
return double.IsInfinity(value.Mantissa);
}
public static BigDouble Parse(string value)
{
if (value.IndexOf('e') != -1)
{
var parts = value.Split('e');
var mantissa = double.Parse(parts[0], CultureInfo.InvariantCulture);
var exponent = long.Parse(parts[1], CultureInfo.InvariantCulture);
return Normalize(mantissa, exponent);
}
if (value == "NaN")
{
return NaN;
}
var result = new BigDouble(double.Parse(value, CultureInfo.InvariantCulture));
if (IsNaN(result))
{
throw new Exception("Invalid argument: " + value);
}
return result;
}
public double ToDouble()
{
if (IsNaN(this))
{
return double.NaN;
}
if (Exponent > DoubleExpMax)
{
return Mantissa > 0 ? double.PositiveInfinity : double.NegativeInfinity;
}
if (Exponent < DoubleExpMin)
{
return 0.0;
}
//SAFETY: again, handle 5e-324, -5e-324 separately
if (Exponent == DoubleExpMin)
{
return Mantissa > 0 ? 5e-324 : -5e-324;
}
var result = Mantissa * PowersOf10.Lookup(Exponent);
if (!IsFinite(result) || Exponent < 0)
{
return result;
}
var resultrounded = Math.Round(result);
if (Math.Abs(resultrounded - result) < 1e-10) return resultrounded;
return result;
}
public override string ToString()
{
return BigNumber.FormatBigDouble(this, null, null);
}
public string ToString(string format)
{
return BigNumber.FormatBigDouble(this, format, null);
}
public string ToString(string format, IFormatProvider formatProvider)
{
return BigNumber.FormatBigDouble(this, format, formatProvider);
}
public static BigDouble Abs(BigDouble value)
{
return FromMantissaExponentNoNormalize(Math.Abs(value.Mantissa), value.Exponent);
}
public static BigDouble Negate(BigDouble value)
{
return FromMantissaExponentNoNormalize(-value.Mantissa, value.Exponent);
}
public static int Sign(BigDouble value)
{
return Math.Sign(value.Mantissa);
}
public static BigDouble Round(BigDouble value)
{
if (IsNaN(value))
{
return value;
}
if (value.Exponent < -1)
{
return Zero;
}
if (value.Exponent < MaxSignificantDigits)
{
return new BigDouble(Math.Round(value.ToDouble()));
}
return value;
}
public static BigDouble Round(BigDouble value, MidpointRounding mode)
{
if (IsNaN(value))
{
return value;
}
if (value.Exponent < -1)
{
return Zero;
}
if (value.Exponent < MaxSignificantDigits)
{
return new BigDouble(Math.Round(value.ToDouble(), mode));
}
return value;
}
public static BigDouble Floor(BigDouble value)
{
if (IsNaN(value))
{
return value;
}
if (value.Exponent < -1)
{
return Math.Sign(value.Mantissa) >= 0 ? Zero : -One;
}
if (value.Exponent < MaxSignificantDigits)
{
return new BigDouble(Math.Floor(value.ToDouble()));
}
return value;
}
public static BigDouble Ceiling(BigDouble value)
{
if (IsNaN(value))
{
return value;
}
if (value.Exponent < -1)
{
return Math.Sign(value.Mantissa) > 0 ? One : Zero;
}
if (value.Exponent < MaxSignificantDigits)
{
return new BigDouble(Math.Ceiling(value.ToDouble()));
}
return value;
}
public static BigDouble Truncate(BigDouble value)
{
if (IsNaN(value))
{
return value;
}
if (value.Exponent < 0)
{
return Zero;
}
if (value.Exponent < MaxSignificantDigits)
{
return new BigDouble(Math.Truncate(value.ToDouble()));
}
return value;
}
public static BigDouble Add(BigDouble left, BigDouble right)
{
//figure out which is bigger, shrink the mantissa of the smaller by the difference in exponents, add mantissas, normalize and return
//TODO: Optimizations and simplification may be possible, see https://github.com/Patashu/break_infinity.js/issues/8
if (IsZero(left.Mantissa))
{
return right;
}
if (IsZero(right.Mantissa))
{
return left;
}
if (IsNaN(left) || IsNaN(right) || IsInfinity(left) || IsInfinity(right))
{
// Let Double handle these cases.
return left.Mantissa + right.Mantissa;
}
BigDouble bigger, smaller;
if (left.Exponent >= right.Exponent)
{
bigger = left;
smaller = right;
}
else
{
bigger = right;
smaller = left;
}
if (bigger.Exponent - smaller.Exponent > MaxSignificantDigits)
{
return bigger;
}
//have to do this because adding numbers that were once integers but scaled down is imprecise.
//Example: 299 + 18
return Normalize(
Math.Round(1e14 * bigger.Mantissa + 1e14 * smaller.Mantissa *
PowersOf10.Lookup(smaller.Exponent - bigger.Exponent)),
bigger.Exponent - 14);
}
public static BigDouble Subtract(BigDouble left, BigDouble right)
{
return left + -right;
}
public static BigDouble Multiply(BigDouble left, BigDouble right)
{
// 2e3 * 4e5 = (2 * 4)e(3 + 5)
return Normalize(left.Mantissa * right.Mantissa, left.Exponent + right.Exponent);
}
public static BigDouble Divide(BigDouble left, BigDouble right)
{
return left * Reciprocate(right);
}
public static BigDouble Reciprocate(BigDouble value)
{
return Normalize(1.0 / value.Mantissa, -value.Exponent);
}
public static implicit operator BigDouble(double value)
{
return new BigDouble(value);
}
public static implicit operator BigDouble(int value)
{
return new BigDouble(value);
}
public static implicit operator BigDouble(long value)
{
return new BigDouble(value);
}
public static implicit operator BigDouble(float value)
{
return new BigDouble(value);
}
public static BigDouble operator -(BigDouble value)
{
return Negate(value);
}
public static BigDouble operator +(BigDouble left, BigDouble right)
{
return Add(left, right);
}
public static BigDouble operator -(BigDouble left, BigDouble right)
{
return Subtract(left, right);
}
public static BigDouble operator *(BigDouble left, BigDouble right)
{
return Multiply(left, right);
}
public static BigDouble operator /(BigDouble left, BigDouble right)
{
return Divide(left, right);
}
public static BigDouble operator ++(BigDouble value)
{
return value.Add(1);
}
public static BigDouble operator --(BigDouble value)
{
return value.Subtract(1);
}
public int CompareTo(object other)
{
if (other == null)
{
return 1;
}
if (other is BigDouble)
{
return CompareTo((BigDouble) other);
}
throw new ArgumentException("The parameter must be a BigDouble.");
}
public int CompareTo(BigDouble other)
{
if (
IsZero(Mantissa) || IsZero(other.Mantissa)
|| IsNaN(this) || IsNaN(other)
|| IsInfinity(this) || IsInfinity(other))
{
// Let Double handle these cases.
return Mantissa.CompareTo(other.Mantissa);
}
if (Mantissa > 0 && other.Mantissa < 0)
{
return 1;
}
if (Mantissa < 0 && other.Mantissa > 0)
{
return -1;
}
var exponentComparison = Exponent.CompareTo(other.Exponent);
return exponentComparison != 0
? (Mantissa > 0 ? exponentComparison : -exponentComparison)
: Mantissa.CompareTo(other.Mantissa);
}
public override bool Equals(object other)
{
return other is BigDouble && Equals((BigDouble)other);
}
public override int GetHashCode()
{
unchecked
{
return (Mantissa.GetHashCode() * 397) ^ Exponent.GetHashCode();
}
}
public bool Equals(BigDouble other)
{
return !IsNaN(this) && !IsNaN(other) && (AreSameInfinity(this, other)
|| Exponent == other.Exponent && AreEqual(Mantissa, other.Mantissa));
}
/// <summary>
/// Relative comparison with tolerance being adjusted with greatest exponent.
/// <para>
/// For example, if you put in 1e-9, then any number closer to the larger number
/// than (larger number) * 1e-9 will be considered equal.
/// </para>
/// </summary>
public bool Equals(BigDouble other, double tolerance)
{
return !IsNaN(this) && !IsNaN(other) && (AreSameInfinity(this, other)
|| Abs(this - other) <= Max(Abs(this), Abs(other)) * tolerance);
}
private static bool AreSameInfinity(BigDouble first, BigDouble second)
{
return IsPositiveInfinity(first) && IsPositiveInfinity(second)
|| IsNegativeInfinity(first) && IsNegativeInfinity(second);
}
public static bool operator ==(BigDouble left, BigDouble right)
{
return left.Equals(right);
}
public static bool operator !=(BigDouble left, BigDouble right)
{
return !(left == right);
}
public static bool operator <(BigDouble a, BigDouble b)
{
if (IsNaN(a) || IsNaN(b))
{
return false;
}
if (IsZero(a.Mantissa)) return b.Mantissa > 0;
if (IsZero(b.Mantissa)) return a.Mantissa < 0;
if (a.Exponent == b.Exponent) return a.Mantissa < b.Mantissa;
if (a.Mantissa > 0) return b.Mantissa > 0 && a.Exponent < b.Exponent;
return b.Mantissa > 0 || a.Exponent > b.Exponent;
}
public static bool operator <=(BigDouble a, BigDouble b)
{
if (IsNaN(a) || IsNaN(b))
{
return false;
}
return !(a > b);
}
public static bool operator >(BigDouble a, BigDouble b)
{
if (IsNaN(a) || IsNaN(b))
{
return false;
}
if (IsZero(a.Mantissa)) return b.Mantissa < 0;
if (IsZero(b.Mantissa)) return a.Mantissa > 0;
if (a.Exponent == b.Exponent) return a.Mantissa > b.Mantissa;
if (a.Mantissa > 0) return b.Mantissa < 0 || a.Exponent > b.Exponent;
return b.Mantissa < 0 && a.Exponent < b.Exponent;
}
public static bool operator >=(BigDouble a, BigDouble b)
{
if (IsNaN(a) || IsNaN(b))
{
return false;
}
return !(a < b);
}
public static BigDouble Max(BigDouble left, BigDouble right)
{
if (IsNaN(left) || IsNaN(right))
{
return NaN;
}
return left > right ? left : right;
}
public static BigDouble Min(BigDouble left, BigDouble right)
{
if (IsNaN(left) || IsNaN(right))
{
return NaN;
}
return left > right ? right : left;
}
public static double AbsLog10(BigDouble value)
{
return value.Exponent + Math.Log10(Math.Abs(value.Mantissa));
}
public static double Log10(BigDouble value)
{
return value.Exponent + Math.Log10(value.Mantissa);
}
public static double Log(BigDouble value, BigDouble @base)
{
return Log(value, @base.ToDouble());
}
public static double Log(BigDouble value, double @base)
{
if (IsZero(@base))
{
return double.NaN;
}
//UN-SAFETY: Most incremental game cases are log(number := 1 or greater, base := 2 or greater). We assume this to be true and thus only need to return a number, not a BigDouble, and don't do any other kind of error checking.
return 2.30258509299404568402 / Math.Log(@base) * Log10(value);
}
public static double Log2(BigDouble value)
{
return 3.32192809488736234787 * Log10(value);
}
public static double Ln(BigDouble value)
{
return 2.30258509299404568402 * Log10(value);
}
public static BigDouble Pow10(double power)
{
return IsInteger(power)
? Pow10((long) power)
: Normalize(Math.Pow(10, power % 1), (long) Math.Truncate(power));
}
public static BigDouble Pow10(long power)
{
return FromMantissaExponentNoNormalize(1, power);
}
public static BigDouble Pow(BigDouble value, BigDouble power)
{
return Pow(value, power.ToDouble());
}
public static BigDouble Pow(BigDouble value, long power)
{
if (Is10(value))
{
return Pow10(power);
}
var mantissa = Math.Pow(value.Mantissa, power);
if (double.IsInfinity(mantissa))
{
// TODO: This is rather dumb, but works anyway
// Power is too big for our mantissa, so we do multiple Pow with smaller powers.
return Pow(Pow(value, 2), (double) power / 2);
}
return Normalize(mantissa, value.Exponent * power);
}
public static BigDouble Pow(BigDouble value, double power)
{
// TODO: power can be greater that long.MaxValue, which can bring troubles in fast track
var powerIsInteger = IsInteger(power);
if (value < 0 && !powerIsInteger)
{
return NaN;
}
return Is10(value) && powerIsInteger ? Pow10(power) : PowInternal(value, power);
}
private static bool Is10(BigDouble value)
{
return value.Exponent == 1 && value.Mantissa - 1 < double.Epsilon;
}
private static BigDouble PowInternal(BigDouble value, double other)
{
//UN-SAFETY: Accuracy not guaranteed beyond ~9~11 decimal places.
//TODO: Fast track seems about neutral for performance. It might become faster if an integer pow is implemented, or it might not be worth doing (see https://github.com/Patashu/break_infinity.js/issues/4 )
//Fast track: If (this.exponent*value) is an integer and mantissa^value fits in a Number, we can do a very fast method.
var temp = value.Exponent * other;
double newMantissa;
if (IsInteger(temp) && IsFinite(temp) && Math.Abs(temp) < ExpLimit)
{
newMantissa = Math.Pow(value.Mantissa, other);
if (IsFinite(newMantissa))
{
return Normalize(newMantissa, (long) temp);
}
}
//Same speed and usually more accurate. (An arbitrary-precision version of this calculation is used in break_break_infinity.js, sacrificing performance for utter accuracy.)
var newexponent = Math.Truncate(temp);
var residue = temp - newexponent;
newMantissa = Math.Pow(10, other * Math.Log10(value.Mantissa) + residue);
if (IsFinite(newMantissa))
{
return Normalize(newMantissa, (long) newexponent);
}
//UN-SAFETY: This should return NaN when mantissa is negative and value is noninteger.
var result = Pow10(other * AbsLog10(value)); //this is 2x faster and gives same values AFAIK
if (Sign(value) == -1 && AreEqual(other % 2, 1))
{
return -result;
}
return result;
}
public static BigDouble Factorial(BigDouble value)
{
//Using Stirling's Approximation. https://en.wikipedia.org/wiki/Stirling%27s_approximation#Versions_suitable_for_calculators
var n = value.ToDouble() + 1;
return Pow(n / 2.71828182845904523536 * Math.Sqrt(n * Math.Sinh(1 / n) + 1 / (810 * Math.Pow(n, 6))), n) * Math.Sqrt(2 * 3.141592653589793238462 / n);
}
public static BigDouble Exp(BigDouble value)
{
return Pow(2.71828182845904523536, value);
}
public static BigDouble Sqrt(BigDouble value)
{
if (value.Mantissa < 0)
{
return new BigDouble(double.NaN);
}
if (value.Exponent % 2 != 0)
{
// mod of a negative number is negative, so != means '1 or -1'
return Normalize(Math.Sqrt(value.Mantissa) * 3.16227766016838, (long) Math.Floor(value.Exponent / 2.0));
}
return Normalize(Math.Sqrt(value.Mantissa), (long) Math.Floor(value.Exponent / 2.0));
}
public static BigDouble Cbrt(BigDouble value)
{
var sign = 1;
var mantissa = value.Mantissa;
if (mantissa < 0)
{
sign = -1;
mantissa = -mantissa;
}
var newmantissa = sign * Math.Pow(mantissa, 1 / 3.0);
var mod = value.Exponent % 3;
if (mod == 1 || mod == -1)
{
return Normalize(newmantissa * 2.1544346900318837, (long) Math.Floor(value.Exponent / 3.0));
}
if (mod != 0)
{
return Normalize(newmantissa * 4.6415888336127789, (long) Math.Floor(value.Exponent / 3.0));
} //mod != 0 at this point means 'mod == 2 || mod == -2'
return Normalize(newmantissa, (long) Math.Floor(value.Exponent / 3.0));
}
public static BigDouble Sinh(BigDouble value)
{
return (Exp(value) - Exp(-value)) / 2;
}
public static BigDouble Cosh(BigDouble value)
{
return (Exp(value) + Exp(-value)) / 2;
}
public static BigDouble Tanh(BigDouble value)
{
return Sinh(value) / Cosh(value);
}
public static double Asinh(BigDouble value)
{
return Ln(value + Sqrt(Pow(value, 2) + 1));
}
public static double Acosh(BigDouble value)
{
return Ln(value + Sqrt(Pow(value, 2) - 1));
}
public static double Atanh(BigDouble value)
{
if (Abs(value) >= 1) return double.NaN;
return Ln((value + 1) / (One - value)) / 2;
}
private static bool IsZero(double value)
{
return Math.Abs(value) < double.Epsilon;
}
private static bool AreEqual(double first, double second)
{
return Math.Abs(first - second) < Tolerance;
}
private static bool IsInteger(double value)
{
return IsZero(Math.Abs(value % 1));
}
private static bool IsFinite(double value)
{
return !double.IsNaN(value) && !double.IsInfinity(value);
}
/// <summary>
/// The BigNumber class implements methods for formatting and parsing big numeric values.
/// </summary>
private static class BigNumber
{
public static string FormatBigDouble(BigDouble value, string format, IFormatProvider formatProvider)
{
if (IsNaN(value)) return "NaN";
if (value.Exponent >= ExpLimit)
{
return value.Mantissa > 0 ? "Infinity" : "-Infinity";
}
int formatDigits;
var formatSpecifier = ParseFormatSpecifier(format, out formatDigits);
switch (formatSpecifier)
{
case 'R':
case 'G':
return FormatGeneral(value, formatDigits);
case 'E':
return FormatExponential(value, formatDigits);
case 'F':
return FormatFixed(value, formatDigits);
}
throw new FormatException($"Unknown string format '{formatSpecifier}'");
}
private static char ParseFormatSpecifier(string format, out int digits)
{
const char customFormat = (char) 0;
digits = -1;
if (string.IsNullOrEmpty(format))
{
return 'R';
}
var i = 0;
var ch = format[i];
if ((ch < 'A' || ch > 'Z') && (ch < 'a' || ch > 'z'))
{
return customFormat;
}
i++;
var n = -1;
if (i < format.Length && format[i] >= '0' && format[i] <= '9')
{
n = format[i++] - '0';
while (i < format.Length && format[i] >= '0' && format[i] <= '9')
{
n = n * 10 + (format[i++] - '0');
if (n >= 10)
break;
}
}
if (i < format.Length && format[i] != '\0')
{
return customFormat;
}
digits = n;
return ch;
}
private static string FormatGeneral(BigDouble value, int places)
{
if (value.Exponent <= -ExpLimit || IsZero(value.Mantissa))
{
return "0";
}
var format = places > 0 ? $"G{places}" : "G";
if (value.Exponent < 21 && value.Exponent > -7)
{
return value.ToDouble().ToString(format, CultureInfo.InvariantCulture);
}
return value.Mantissa.ToString(format, CultureInfo.InvariantCulture)
+ "E" + (value.Exponent >= 0 ? "+" : "")
+ value.Exponent.ToString(CultureInfo.InvariantCulture);
}
private static string ToFixed(double value, int places)
{
return value.ToString($"F{places}", CultureInfo.InvariantCulture);
}
private static string FormatExponential(BigDouble value, int places)
{
if (value.Exponent <= -ExpLimit || IsZero(value.Mantissa))
{
return "0" + (places > 0 ? ".".PadRight(places + 1, '0') : "") + "E+0";
}
var len = (places >= 0 ? places : MaxSignificantDigits) + 1;
var numDigits = (int)Math.Ceiling(Math.Log10(Math.Abs(value.Mantissa)));
var rounded = Math.Round(value.Mantissa * Math.Pow(10, len - numDigits)) * Math.Pow(10, numDigits - len);
var mantissa = ToFixed(rounded, Math.Max(len - numDigits, 0));
if (mantissa != "0" && places < 0)
{
mantissa = mantissa.TrimEnd('0', '.');
}
return mantissa + "E" + (value.Exponent >= 0 ? "+" : "")
+ value.Exponent;
}
private static string FormatFixed(BigDouble value, int places)
{
if (places < 0)
{
places = MaxSignificantDigits;
}
if (value.Exponent <= -ExpLimit || IsZero(value.Mantissa))
{
return "0" + (places > 0 ? ".".PadRight(places + 1, '0') : "");
}
// two cases:
// 1) exponent is 17 or greater: just print out mantissa with the appropriate number of zeroes after it
// 2) exponent is 16 or less: use basic toFixed
if (value.Exponent >= MaxSignificantDigits)
{
// TODO: StringBuilder-optimizable
return value.Mantissa
.ToString(CultureInfo.InvariantCulture)
.Replace(".", "")
.PadRight((int)value.Exponent + 1, '0')
+ (places > 0 ? ".".PadRight(places + 1, '0') : "");
}
return ToFixed(value.ToDouble(), places);
}
}
/// <summary>
/// We need this lookup table because Math.pow(10, exponent) when exponent's absolute value
/// is large is slightly inaccurate. you can fix it with the power of math... or just make
/// a lookup table. Faster AND simpler.
/// </summary>
private static class PowersOf10
{
private static double[] Powers { get; } = new double[DoubleExpMax - DoubleExpMin];
private const long IndexOf0 = -DoubleExpMin - 1;
static PowersOf10()
{
var index = 0;
for (var i = 0; i < Powers.Length; i++)
{
Powers[index++] = double.Parse("1e" + (i - IndexOf0), CultureInfo.InvariantCulture);
}
}