Repository navigation
Expand file tree
/
Copy pathTransformations.cs
More file actions
2110 lines (1994 loc) · 124 KB
/
Copy pathTransformations.cs
File metadata and controls
2110 lines (1994 loc) · 124 KB
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) 2019-2022 Angouri.
// AngouriMath is licensed under MIT.
// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.
// Website: https://am.angouri.org.
//
using AngouriMath.Core.Multithreading;
using PeterO.Numbers;
using System;
using System.Linq;
using static AngouriMath.Entity;
using static AngouriMath.Entity.Number;
namespace AngouriMath.Functions.Algebra
{
partial class LimitFunctional
{
/// <summary>
/// A vanishing function written as the vanishing argument it is equivalent to, where
/// that argument is what vanishes. <c>sin(u) / u</c>, <c>tan(u) / u</c>,
/// <c>arcsin(u) / u</c> and <c>arctan(u) / u</c> all tend to 1 as u tends to 0, so one
/// may be written for the other in a product or a quotient without changing its limit.
/// </summary>
/// <remarks>
/// The argument's own limit is what the equivalence needs, not the function's. sin(x)
/// vanishes at pi as surely as at 0 and is not equivalent to x there -- it is equivalent
/// to pi - x -- so rewriting it as x turned <c>lim x->pi sin(x) / (x - pi)</c>, which
/// is -1, into pi / 0.
/// </remarks>
private static Entity EquivalenceRules(Entity expr, Variable x, Entity dest)
=> expr is (Sinf or Tanf or Arcsinf or Arctanf)
&& EvalAssumingContinuous(expr.DirectChildren[0].Limit(x, dest)) == 0
? expr.DirectChildren[0]
: expr;
internal static Entity EvalAssumingContinuous(Entity expr) =>
expr.Evaled switch
{
Providedf(var inner, _) => inner,
var x => x
};
/// <summary>
/// How close in the approach is sampled when asking whether a function stays real on
/// the way to its destination. Powers of ten rather than a fixed step, because what
/// matters is near and not evenly spaced: <c>sqrt(x - 1)</c> is real just to the left
/// of 2 and not just to the left of 1, and only the nearer samples tell those apart.
/// </summary>
/// <remarks>
/// It stops at a thousandth, and the reason is cost rather than principle. The sample
/// point goes into the expression, and an expression may put it in an exponent:
/// <c>(1 + x)^(1/x)</c> at 1e-9 is <c>1.000000001</c> raised to a billion, evaluated
/// at a hundred digits, and asking that six times on every limit the machinery takes
/// turned a 20 ms limit into a timeout.
/// <para/>
/// Sampling less far in only ever *misses* a function that leaves the reals nearer the
/// destination than this reaches, and a miss leaves the limit answered exactly as it
/// was before. The guard withdraws on evidence and never on the absence of it, so the
/// cheap end of that trade is the safe one.
/// </remarks>
[ConstantField] private static readonly int[] ApproachScales = { 1, 2, 3 };
/// <summary>
/// Whether the expression takes values outside the reals on the way in. Under a real
/// codomain such a limit has no value, rather than the value its complex continuation
/// approaches.
/// </summary>
/// <remarks>
/// <c>lim x->0- ln(x)</c> is the plain case: the logarithm of a negative real is
/// <c>ln|x| + i*pi</c>, and answering <c>-oo</c> reports the magnitude of something
/// that is not a real number at any point of the approach.
/// <para/>
/// Decided by sampling rather than symbolically, and deliberately: what is being asked
/// is whether the function *takes* non-real values near a point, which no property of
/// the tree answers. The direction of error is chosen too. A sample that cannot be
/// evaluated, or that comes back non-finite, is passed over rather than counted, and an
/// expression carrying a second variable is not judged at all -- so the answer is only
/// ever "yes, demonstrably" or "not shown", and a limit is withdrawn on evidence.
/// <a href="https://github.com/asc-community/AngouriMath/issues/719">#719</a>
/// </remarks>
private static bool LeavesTheRealsOnTheApproach(Entity expr, Variable x, Entity dest, ApproachFrom side)
{
if (expr.Vars.Count() != 1)
return false;
var towardsNegative = side is ApproachFrom.Left;
if (!dest.IsFinite)
towardsNegative = dest.Evaled is Real { IsNegative: true };
foreach (var scale in ApproachScales)
{
var ten = EInteger.FromInt32(10).Pow(scale);
Entity point;
if (dest.IsFinite)
{
var step = (Entity)Rational.Create(EInteger.One, ten);
point = towardsNegative ? dest - step : dest + step;
}
else
{
var far = (Entity)Integer.Create(ten);
point = towardsNegative ? -far : far;
}
if (expr.Substitute(x, point).Evaled is not Complex value || !value.IsFinite)
continue;
var imaginary = value.ImaginaryPart.EDecimal.Abs();
var real = value.RealPart.EDecimal.Abs();
// Relative, since the point may be evaluated at a scale where an absolute
// threshold means nothing, and a rounding artefact must not withdraw a limit.
if (imaginary.GreaterThan(EDecimal.Create(1, -6).Multiply(EDecimal.Max(real, EDecimal.One, null))))
return true;
}
return false;
}
/// <summary>
/// Whether the reading in force is of real-valued functions, in which case a limit
/// reached only through the complex plane is not one.
/// </summary>
internal static bool RealCodomainWithdraws(Entity expr, Variable x, Entity dest, ApproachFrom side)
=> MathS.Settings.Codomain.Value is AngouriMath.Core.Domain.Real
&& LeavesTheRealsOnTheApproach(expr, x, dest, side);
private static Entity ApplyFirstRemarkable(Entity expr, Variable x, Entity dest)
=> expr switch
{
Divf(var a, var b) div
when EvalAssumingContinuous(a.Limit(x, dest)) == 0 && EvalAssumingContinuous(b.Limit(x, dest)) == 0
=> div.New(EquivalenceRules(a, x, dest), EquivalenceRules(b, x, dest)),
// A product takes the substitution as much as a quotient does -- it is the ratio
// of the two forms tending to 1 that licenses it, and that says nothing about
// which of them the rest of the expression is written over. Only the quotient
// had it, so lim x->0+ tan(x) * ln(x) went the long way round through l'Hopital's
// rule and came back NaN, where the same limit written sin(x) * ln(x) is 0.
Mulf(var a, var b)
when EquivalenceRules(a, x, dest) is var equivalentA
&& EquivalenceRules(b, x, dest) is var equivalentB
&& (!ReferenceEquals(equivalentA, a) || !ReferenceEquals(equivalentB, b))
=> equivalentA * equivalentB,
_ => expr
};
/// <summary>
/// <see cref="ApplyFirstRemarkable"/> applied down the product-and-quotient spine
/// rather than at the root alone.
/// </summary>
/// <remarks>
/// The rule matches a product or a quotient whose own child is a vanishing sine, so a
/// constant factor written to the left pushes that sine one level down and out of
/// reach: <c>2 * sin(1/x) * x</c> parses as <c>(2 * sin(1/x)) * x</c>, whose children
/// are a product and a variable. The descent then reads it as <c>0 * (+oo)</c> and is
/// definite about it, while the same product written <c>sin(1/x) * x * 2</c> answers 2.
/// Which side a caller writes a constant on is not a mathematical difference, and
/// simplification produces either.
/// <para/>
/// **Not a plain <c>Replace</c>, and that is the whole of what keeps it sound.** The
/// equivalence holds for a *factor* of the expression as a whole -- if <c>f/g -> 1</c>
/// then <c>f*h</c> and <c>g*h</c> go to the same place -- and not for a term of a sum,
/// where the difference between <c>f</c> and <c>g</c> is the entire answer. Rewriting
/// the sine inside <c>(sin(x)/x - 1)/x^2</c> would answer 0 where the limit is -1/6.
/// Stopping at anything that is not a product or a quotient keeps every rewrite to a
/// factor of the whole.
/// <a href="https://github.com/asc-community/AngouriMath/issues/749">#749</a>
/// </remarks>
private static Entity ApplyFirstRemarkableOverFactors(Entity expr, Variable x, Entity dest)
{
var applied = ApplyFirstRemarkable(expr, x, dest);
if (applied is not (Mulf or Divf))
return applied;
var left = ApplyFirstRemarkableOverFactors(applied.DirectChildren[0], x, dest);
var right = ApplyFirstRemarkableOverFactors(applied.DirectChildren[1], x, dest);
// Rebuilt only where a factor actually changed, so an expression the rule has
// nothing to say about comes back as the very node it went in as, keeping whatever
// the rest of the machinery has already cached against it.
if (ReferenceEquals(left, applied.DirectChildren[0])
&& ReferenceEquals(right, applied.DirectChildren[1]))
return applied;
return applied is Mulf ? left * right : left / right;
}
private static Entity ApplySecondRemarkable(Entity expr, Variable x, Entity dest)
=> expr switch
{
// f(x)^g(x) for f(x) -> 1, g(x) -> +oo
// => (1 + (f(x) - 1)) ^ g(x) = ((1 - (f(x) - 1)) ^ (1 / (f(x) - 1))) ^ (g(x) (f(x) - 1))
// e ^ (g(x) * (f(x) - 1))
Powf(var xPlusOne, var xPower) when
xPlusOne.ContainsNode(x) && xPower.ContainsNode(x) &&
EvalAssumingContinuous((xPlusOne - 1).Limit(x, dest)) == 0 && DivergesInMagnitude(xPower, x, dest) =>
// The exponent as the quotient (f - 1) / (1/g), not the product g (f - 1): a 0/0 the descent hands to the
// whole limit, where it read 0 * oo as NaN, and (cos(x))^(1/x^2) at 0, e^(-1/2), was NaN.
MathS.e.Pow((xPlusOne - 1) / (1 / xPower)),
// a(x)^n / b(x)^n, the same limit written as a quotient. The simplifier used
// to gather this into (a/b)^n for us, which is how the shape reached the rule
// above at all -- and that gathering is false across the branch cuts, since
// sqrt(2)/sqrt(-3) is -0.8165i where (2/-3)^(1/2) is +0.8165i.
// https://github.com/asc-community/AngouriMath/issues/802
//
// Read here instead, it is sound: a limit only needs the identity to hold in a
// neighbourhood of the destination, and both bases are required to be
// eventually positive on the way there -- where their arguments are both zero
// and there is no turn of the argument to lose. That is checkable, which is
// exactly what it is not in the simplifier, where the expression has no
// destination to be near.
Divf(Powf(var numeratorBase, var power), Powf(var denominatorBase, var powerAgain)) when
power == powerAgain && numeratorBase.ContainsNode(x) && denominatorBase.ContainsNode(x)
&& power.ContainsNode(x)
&& IsEventuallyPositive(numeratorBase, x, dest) && IsEventuallyPositive(denominatorBase, x, dest)
&& EvalAssumingContinuous((numeratorBase / denominatorBase - 1).Limit(x, dest)) == 0
&& DivergesInMagnitude(power, x, dest) =>
MathS.e.Pow((numeratorBase / denominatorBase - 1) / (1 / power)),
_ => expr
};
/// <summary>
/// Whether a base stays positive on the approach to <paramref name="dest"/>, which is
/// what makes gathering a quotient of two powers into one power sound *here* when it
/// is not sound in general: two positive bases have argument zero apiece, so their
/// quotient's argument cannot leave the principal branch.
/// </summary>
private static bool IsEventuallyPositive(Entity expr, Variable x, Entity dest)
{
var limit = EvalAssumingContinuous(expr.Limit(x, dest));
return limit == Real.PositiveInfinity || limit is Real { IsPositive: true };
}
/// <summary>
/// The sign an expression settles on approaching <paramref name="dest"/>: <c>1</c> where
/// it stays positive, <c>-1</c> where it stays negative, <c>0</c> where neither can be
/// read -- a limit of zero, a non-real one, or none at all.
/// </summary>
private static int SignOnTheApproach(Entity expr, Variable x, Entity dest)
{
var limit = EvalAssumingContinuous(expr.Limit(x, dest));
if (limit == Real.PositiveInfinity) return 1;
if (limit == Real.NegativeInfinity) return -1;
return limit switch
{
Real { IsPositive: true } => 1,
Real { IsNegative: true } => -1,
_ => 0
};
}
/// <summary>
/// <see cref="SignOnTheApproach"/>, asked once per expression per approach. An
/// <see cref="Entity"/> hashes structurally, so the same operand written the same way is
/// the same key.
/// </summary>
private static int MemoisedSign(Entity expr, Approach approach)
{
var key = (approach.Dest, expr);
if (signMemo is { } memo && memo.TryGetValue(key, out var known))
return known;
var sign = SignOnTheApproach(expr, approach.X, approach.Dest);
if (signMemo is { } store)
store[key] = sign;
return sign;
}
/// <summary>
/// How deep <see cref="MayGatherLogarithmsHere"/> may re-enter itself. It asks for a
/// limit per operand, and those limits run the machinery the question was asked from.
/// </summary>
private const int MaxGatherLogarithmsDepth = 1;
[System.ThreadStatic] private static int gatherLogarithmsDepth;
/// <summary>
/// The approach the limit machinery is currently reading an expression on, or
/// <see langword="null"/> where an expression is being simplified on its own account.
/// </summary>
/// <remarks>
/// This is the one thing a simplification rule cannot work out for itself and the limit
/// machinery can: *where the expression is going*. <c>ln(a) + ln(b) = ln(a*b)</c> is
/// false off the positive reals, so <c>Simplify</c> may not apply it to a symbol -- but
/// on a stated approach the sign of each operand is decidable, and where the two signs
/// agree the identity is exact. Without this the rule would have to be either unsound
/// (as it was) or absent, and absent costs termination rather than coverage: the limit
/// machinery's own expansion creates logarithm pairs that only this can put back
/// together. https://github.com/asc-community/AngouriMath/issues/721
/// <para/>
/// Thread-static because the limit machinery is synchronous and every other setting here
/// is; it is swapped rather than set, so a nested reading restores the outer one.
/// </remarks>
[System.ThreadStatic] private static Approach? currentApproach;
/// <summary>
/// A destination being approached, and the signs already established against it.
/// </summary>
/// <remarks>
/// The memo is not an optimisation to be taken or left. The rule is asked once per match
/// per candidate the simplifier generates, and it is asked about the *same* operands over
/// and over: <c>lim x->-oo (x-5)^x / x^x</c> put the same pair to it 192 times. Each
/// answer costs two limits, which run this whole machinery, so without the memo the
/// #596 limit stops finishing inside the minute its own test allows it.
/// </remarks>
internal readonly record struct Approach(Variable X, Entity Dest);
/// <summary>
/// The signs already established, keyed by the destination they were established against
/// as well as by the expression, and shared by every approach inside the outermost one.
/// </summary>
/// <remarks>
/// A memo per approach is very nearly no memo at all: the limit machinery re-enters
/// itself constantly and asks about the same operands each time -- one computation put
/// the same pair to the rule 192 times, and each answer costs two limits, which run this
/// whole machinery. It is dropped when the outermost approach is left, so nothing
/// survives a call.
/// </remarks>
[System.ThreadStatic] private static Dictionary<(Entity Dest, Entity Expr), int>? signMemo;
[System.ThreadStatic] private static int approachDepth;
/// <summary>
/// Whether an approach is being read, and so whether a simplification can answer
/// otherwise than it would on its own account: <see cref="MayGatherLogarithmsHere"/> and
/// <see cref="MayTakeLogOfPowerHere"/> fire only then.
/// </summary>
internal static bool IsReadingAnApproach => currentApproach is not null;
/// <summary>
/// States that <paramref name="x"/> is being read on its way to <paramref name="dest"/>,
/// and returns the previous approach for <see cref="LeaveApproach"/> to put back.
/// </summary>
internal static Approach? EnterApproach(Variable x, Entity dest)
{
var previous = currentApproach;
approachDepth++;
signMemo ??= new();
currentApproach = new Approach(x, dest);
return previous;
}
/// <summary>
/// Puts back what <see cref="EnterApproach"/> returned, and drops the memo once the
/// outermost approach is left.
/// </summary>
internal static void LeaveApproach(Approach? previous)
{
currentApproach = previous;
if (--approachDepth == 0)
signMemo = null;
}
/// <summary>
/// Installs <paramref name="approach"/> as the current one and returns the previous, for
/// the caller to put back.
/// </summary>
internal static Approach? SwapApproach(Approach? approach)
{
var previous = currentApproach;
currentApproach = approach;
return previous;
}
/// <summary>
/// Whether the simplifier's logarithm gathering may fire here, which it may only while
/// an approach is being read and only where the operands hold their sign on it.
/// </summary>
/// <remarks>
/// The approach is withdrawn for the duration of the check, so that the limits it asks
/// for cannot come back through this same door -- conservative, and it terminates.
/// </remarks>
internal static bool MayGatherLogarithmsHere(Entity left, Entity right, bool isDifference)
{
if (currentApproach is not { } approach || gatherLogarithmsDepth >= MaxGatherLogarithmsDepth)
return false;
gatherLogarithmsDepth++;
var previous = SwapApproach(null);
try
{
var leftSign = MemoisedSign(left, approach);
if (leftSign == 0)
return false;
var rightSign = MemoisedSign(right, approach);
return isDifference ? leftSign == rightSign : leftSign == 1 && rightSign == 1;
}
finally { SwapApproach(previous); gatherLogarithmsDepth--; }
}
/// <summary>
/// Whether <c>log_b(a^c) = c * log_b(a)</c> may be applied here, which it may only while
/// an approach is being read, and only where <paramref name="base"/> holds a positive
/// sign on it and <paramref name="exponent"/> is real along it.
/// </summary>
/// <remarks>
/// The identity needs <c>Im(c * ln a)</c> inside the strip <c>(-pi, pi]</c>. A base that
/// is positive on the approach makes <c>ln a</c> real, and a real <c>c</c> then leaves the
/// product real, so there is nothing for the principal branch to discard. Both halves are
/// answerable here and neither is answerable to a simplifier reading the expression on its
/// own account, which is why the rule declines there.
/// <para/>
/// The approach is withdrawn for the duration of the sign check, as in
/// <see cref="MayGatherLogarithmsHere"/>, so the limits it asks for cannot come back
/// through this same door.
/// https://github.com/asc-community/AngouriMath/issues/902
/// </remarks>
internal static bool MayTakeLogOfPowerHere(Entity @base, Entity exponent)
{
if (currentApproach is not { } approach || logOfPowerDepth >= MaxLogOfPowerDepth)
return false;
// A destination off the real line is not an approach along it, and then nothing below
// can be said about the variable.
if (approach.Dest.Evaled is not Real)
return false;
// The sign check below reads the base's limit, and a limit being positive does not
// make the base real on the way to it -- x + i*sin(x) tends to +oo off the real line.
if (!IsRealAlong(@base, approach.X) || !IsRealAlong(exponent, approach.X))
return false;
logOfPowerDepth++;
var previous = SwapApproach(null);
try
{
return MemoisedSign(@base, approach) == 1;
}
finally { SwapApproach(previous); logOfPowerDepth--; }
}
/// <summary>
/// How deep <see cref="MayTakeLogOfPowerHere"/> may re-enter itself, for the reason
/// <see cref="MaxGatherLogarithmsDepth"/> gives: it asks for a limit, and that limit runs
/// the machinery the question was asked from.
/// </summary>
private const int MaxLogOfPowerDepth = 1;
[System.ThreadStatic] private static int logOfPowerDepth;
/// <summary>
/// Whether <paramref name="expr"/> is real wherever <paramref name="x"/> is, decided
/// structurally. On an approach to a real destination the variable runs along the real
/// line, which is the one thing that makes this answerable for a symbol at all.
/// </summary>
/// <remarks>
/// A power is admitted only with a whole exponent or a decidably positive base, because a
/// real raised to a real leaves the real line as soon as the base goes negative:
/// <c>(-2)^(1/2)</c> is imaginary. Any other symbol answers <see langword="false"/>, since
/// a second variable carries no approach and may be complex. Anything unlisted answers
/// <see langword="false"/> as well, which costs coverage and never correctness.
/// </remarks>
private static bool IsRealAlong(Entity expr, Variable x)
{
// Anything closed that evaluates to a finite real is one, which is how pi and e get
// in: both are Variable here, and neither is the approach variable.
if (expr.Evaled is Real { EDecimal.IsFinite: true })
return true;
return expr switch
{
Variable v => v == x,
Sumf(var a, var b) => IsRealAlong(a, x) && IsRealAlong(b, x),
Minusf(var a, var b) => IsRealAlong(a, x) && IsRealAlong(b, x),
Mulf(var a, var b) => IsRealAlong(a, x) && IsRealAlong(b, x),
Divf(var a, var b) => IsRealAlong(a, x) && IsRealAlong(b, x),
Absf => true,
Powf(var b, Integer) => IsRealAlong(b, x),
Powf(var b, var e) => IsRealAlong(e, x) && b.Evaled is Real { IsPositive: true },
_ => false
};
}
/// <summary>
/// How many times over <see cref="ApplySecondRemarkable"/> may be re-read into an
/// expression that <see cref="SimplifyAndComputeLimitToInfinity"/>'s simplification
/// has just created.
/// </summary>
/// <remarks>
/// The rewrite puts the base under an <c>e</c>, which the rule's own pattern requires
/// to contain the variable and so does not match, meaning it cannot feed itself
/// directly. This guards the indirect route -- a simplification that reads
/// <c>e^(g * (f - 1))</c> back as a power whose exponent moves -- and the cost, since
/// every level of it asks for limits of its own.
/// </remarks>
private const int MaxSecondRemarkableRereads = 3;
[ThreadStatic] private static int secondRemarkableRereads;
/// <summary>
/// Whether a re-reading of the second remarkable limit may still be attempted.
/// </summary>
private static bool MaySecondRemarkableBeReread => secondRemarkableRereads < MaxSecondRemarkableRereads;
/// <summary>
/// The limit of f(x)^g(x) where the pair is indeterminate and the second remarkable
/// limit does not already cover it -- that is, 0^0 and oo^0 -- or <see langword="null"/>
/// where that is not the shape or the exponent settles nothing.
/// </summary>
/// <remarks>
/// The descent substitutes each part's own limit, so both of these arrive as 0^0, which
/// is NaN. Written over as e^(g * ln f), the same question is the limit of a product of
/// something vanishing with something diverging, which the rules below can take apart.
/// <para/>
/// The exponent is asked as a limit of its own rather than rewritten in place, because a
/// rewrite would only hand the descent a product it reads no better than the power: the
/// descent substitutes the parts' limits and does not apply l'Hopital's rule to a part.
/// Asking outright is what puts the whole machinery behind the exponent.
/// <para/>
/// 1^oo is left to <see cref="ApplySecondRemarkable"/>, which answers it more directly,
/// and 0^oo and oo^oo are not indeterminate at all.
/// </remarks>
internal static Entity? SolveAsIndeterminatePower(Entity expr, Variable x, Entity dest, ApproachFrom side)
{
if (expr is not Powf(var @base, var power)
|| !@base.ContainsNode(x) || !power.ContainsNode(x)
|| indeterminatePowerDepth >= MaxIndeterminatePowerDepth)
return null;
if (EvalAssumingContinuous(power.Limit(x, dest, side)) != 0)
return null;
// f^g is e^(g * ln f), and this rule computes the limit of the exponent. Where the
// base holds a diverging factorial, that logarithm is what Stirling's expansion is
// stated for -- so the expansion is applied here, to the exponent, rather than to
// the base, where it would have to reproduce the factorial itself and its merely
// *relative* error. https://github.com/asc-community/AngouriMath/issues/754
var byStirling = StirlingExponent(@base, power, x, dest);
if (byStirling is null)
{
var baseLimit = EvalAssumingContinuous(@base.Limit(x, dest, side));
// A base tending to a number other than 0 is not an indeterminate form, and
// its limit is the limit's power: g * ln(f) tends to 0 whatever the branch of
// ln(f), which stays bounded on the cut too, so f^g tends to 1. Answered here
// rather than left to the descent, which asks the base's limit by its own
// reading and can decline what this one has just taken:
// lim x->0+ log(x, tanh(x))^(x^(pi + x)) is 1, and was answered only while
// an undecided base was taken for an infinite one.
if (IsFiniteNode(baseLimit) && baseLimit.Evaled is Complex { IsZero: false } finite && finite.IsFinite)
return Integer.One;
if (baseLimit != 0 && !IsInfiniteNode(baseLimit))
return null;
// Every route out of ln(f) runs through differentiating f, so a base this
// library cannot differentiate is one the rewrite cannot finish on: it would
// only hand the rules an expression with a hole in it and let them work at it.
// A factorial is the case that matters -- its derivative wants the digamma
// function, which is not here, and comes back as NaN. That is why the expansion
// above is tried first: where it applies there is no factorial left to
// differentiate, and this guard is asking about an expression the rule is no
// longer going to use.
var derivative = @base.Differentiate(x).InnerSimplified;
if (derivative.Nodes.Any(node => node is Derivativef || node == MathS.NaN))
return null;
}
indeterminatePowerDepth++;
try
{
var exponentExpr = byStirling ?? (power * MathS.Ln(@base)).InnerSimplified;
if (ComputeLimit(exponentExpr, x, dest, side) is not { } exponent
|| exponent.Evaled == MathS.NaN)
return null;
return MathS.e.Pow(exponent).InnerSimplified;
}
finally { indeterminatePowerDepth--; }
}
/// <summary>
/// <c>power * ln(base)</c> with the logarithm of every diverging factorial in it
/// replaced by Stirling's expansion, or <see langword="null"/> where there is no such
/// factorial or the expansion would not be sound here.
/// </summary>
/// <remarks>
/// <c>ln(f!)</c> is <c>f*ln(f) - f + ln(2*pi*f)/2 + 1/(12f) + O(1/f^3)</c>, and what is
/// dropped **vanishes** -- where the asymptotic for <c>f!</c> itself has an error that
/// is merely relative. That is why the expansion is written for the logarithm and
/// applied to this exponent rather than substituted for the factorial in the base.
/// <para/>
/// Vanishing is still not sufficient, because the dropped term is multiplied by the
/// exponent the rewrite sits under: the answer is <c>e^(power * ln(base))</c>, so an
/// error of <c>1/(12f)</c> in the logarithm contributes <c>power/(12f)</c> to the
/// exponent. Requiring <c>power / f -> 0</c> is what makes it disappear. For
/// <c>((x!) / x^x)^(1/x)</c> that ratio is <c>1/x^2</c>.
/// <para/>
/// The logarithm has to be taken apart before the factorial's own is visible:
/// <c>ln(x!/x^x)</c> is one node, and nothing here simplifies it. Splitting it over
/// products, quotients and powers assumes the parts are positive on the approach, which
/// is the same assumption the simplifier's <c>ln(a) + ln(b) = ln(a*b)</c> already
/// makes; it is confined to logarithms that actually hold a diverging factorial, so it
/// is reached only by expressions that have no answer at all without it.
/// <a href="https://github.com/asc-community/AngouriMath/issues/754">#754</a>
/// </remarks>
private static Entity? StirlingExponent(Entity @base, Entity power, Variable x, Entity dest)
{
var factorials = @base.Nodes.OfType<Factorialf>()
.Where(f => f.Argument.ContainsNode(x)
&& EvalAssumingContinuous(f.Argument.Limit(x, dest)) == Real.PositiveInfinity)
.ToList();
if (factorials.Count == 0)
return null;
// The dropped 1/(12f) is multiplied by the exponent this sits under, so it only
// disappears where power/f does.
foreach (var factorial in factorials)
if (EvalAssumingContinuous((power / factorial.Argument).Limit(x, dest)) != 0)
return null;
return (power * LogarithmExpanded(@base, x, dest)).InnerSimplified;
}
/// <summary>
/// Stirling's expansion of <c>ln(f!)</c>, whose error is the vanishing
/// <c>1/(12f) + O(1/f^3)</c>.
/// </summary>
private static Entity StirlingSeries(Entity argument)
=> argument * MathS.Ln(argument) - argument + MathS.Ln(2 * MathS.pi * argument) / 2;
/// <summary>
/// The expression with the logarithm of every diverging factorial in it replaced by
/// Stirling's expansion, or <see langword="null"/> where there is none or the error the
/// expansion drops would not vanish out of the answer.
/// </summary>
/// <remarks>
/// <see cref="StirlingExponent"/> can state its guard as <c>power / f -> 0</c> because
/// it knows the shape it is working in: the answer there is
/// <c>e^(power * ln(base))</c>, so <c>power</c> *is* the coefficient the dropped
/// <c>1/(12f)</c> gets multiplied by. Anywhere else that coefficient has to be found
/// rather than read off, and it is found by putting a variable where the logarithm is
/// and differentiating with respect to it.
/// <para/>
/// This is not a rewrite that may be applied wherever a factorial's logarithm appears.
/// <c>x * (ln(x!) - (x*ln(x) - x + ln(2*pi*x)/2))</c> is <c>1/12</c> -- an expression
/// built out of the dropped term itself -- and a rewrite that did not ask would answer
/// it <c>0</c>. There the coefficient is <c>x</c> and <c>x / x</c> does not vanish, so
/// it is refused. For <c>ln(x!) / x</c> the coefficient is <c>1/x</c> and the ratio is
/// <c>1/x^2</c>, so it is allowed.
/// <para/>
/// The coefficient is put back in terms of the logarithm before it is judged, since an
/// expression need not be linear in it: for <c>ln(x!)^2</c> the derivative is
/// <c>2*ln(x!)</c>, which grows like <c>2*x*ln(x)</c> and is refused -- correctly, as
/// the difference of the squares is <c>ln(x)/6</c> and diverges.
/// <a href="https://github.com/asc-community/AngouriMath/issues/765">#765</a>
/// </remarks>
private static Entity? StirlingRewritten(Entity expr, Variable x, Entity dest)
{
var logarithms = expr.Nodes
.OfType<Logf>()
.Where(logarithm => logarithm.Base == MathS.e
&& DivergingFactorials(logarithm.Antilogarithm, x, dest).Count > 0)
.Distinct()
.ToList();
if (logarithms.Count == 0)
return null;
var rewritten = expr;
foreach (var logarithm in logarithms)
{
var probe = Variable.CreateTemp(expr.Vars);
var coefficient = expr.Substitute(logarithm, probe)
.Differentiate(probe).InnerSimplified.Substitute(probe, logarithm);
if (coefficient.Nodes.Any(node => node is Derivativef || node == MathS.NaN))
return null;
// The logarithm may hold several factorials, and what the expansion drops from
// it is the sum of their 1/(12f). Each has to vanish against the coefficient.
foreach (var factorial in DivergingFactorials(logarithm.Antilogarithm, x, dest))
if (EvalAssumingContinuous((coefficient / factorial.Argument).Limit(x, dest)) != 0)
return null;
rewritten = rewritten.Substitute(logarithm,
LogarithmExpanded(logarithm.Antilogarithm, x, dest));
}
return rewritten;
}
/// <summary>
/// Whether an expression is already being read through its own logarithm further up,
/// in which case doing it again buys nothing and costs a great deal.
/// </summary>
[ThreadStatic] private static bool substitutingFactorial;
/// <summary>
/// The fixed power of <paramref name="target"/> that <paramref name="expr"/> depends
/// on, or <see langword="null"/> where there is no such power.
/// </summary>
/// <remarks>
/// Once the expression is read through its logarithm, <c>ln(expr)</c> holds
/// <c>ln(target)</c> multiplied by exactly this power -- so it is the coefficient the
/// dropped <c>1/(12f)</c> arrives with, and the same guard as everywhere else applies
/// to it. Only multiplication, division and a constant power keep a factor a factor; a
/// sum does not (<c>x! + x</c> is not a fixed power of the factorial at all), and
/// neither does an exponent that moves -- for <c>(x!)^x</c> the power is <c>x</c>,
/// <c>x/(12x)</c> does not vanish, and it is refused.
/// <para/>
/// Read off the shape rather than by differentiating and simplifying. That is the same
/// answer at a fraction of the cost: the symbolic route needs a full
/// <see cref="Entity.Simplify"/> to cancel the target back out -- <c>InnerSimplified</c>
/// leaves <c>p * (1/x^x) / (p/x^x)</c> standing -- and it is asked on every expression
/// holding a factorial.
/// </remarks>
private static int? PowerItAppearsTo(Entity expr, Entity target, Variable x)
{
if (expr == target)
return 1;
if (!expr.ContainsNode(target))
return 0;
switch (expr)
{
case Mulf(var multiplier, var multiplicand):
return PowerItAppearsTo(multiplier, target, x)
+ PowerItAppearsTo(multiplicand, target, x);
case Divf(var dividend, var divisor):
return PowerItAppearsTo(dividend, target, x)
- PowerItAppearsTo(divisor, target, x);
case Powf(var @base, var exponent)
when !exponent.ContainsNode(x) && !exponent.ContainsNode(target)
&& exponent.Evaled is Integer power:
return PowerItAppearsTo(@base, target, x) * (int)power;
default:
return null;
}
}
/// <summary>
/// The distinct factorials in an expression whose argument runs off to infinity, which
/// are the ones Stirling's expansion is stated for.
/// </summary>
private static List<Factorialf> DivergingFactorials(Entity expr, Variable x, Entity dest)
=> expr.Nodes
.OfType<Factorialf>()
.Where(factorial => factorial.Argument.ContainsNode(x)
&& EvalAssumingContinuous(factorial.Argument.Limit(x, dest))
== Real.PositiveInfinity)
.Distinct()
.ToList();
/// <summary>
/// The logarithm of an expression holding a diverging factorial, with Stirling's
/// expansion written into it -- so that the limit is <c>e</c> to the limit of this --
/// or <see langword="null"/> where there is no such factorial or the expansion would
/// not be sound.
/// </summary>
/// <remarks>
/// <see cref="StirlingRewritten"/> reaches a factorial only where a logarithm is
/// already written down, and <c>x! / x^x</c> has none, so that shape had no limit at
/// all. It is read here by supplying the logarithm: for a positive expression
/// <c>lim H</c> is <c>e^(lim ln H)</c>, and <c>ln H</c> is where the expansion applies.
/// <para/>
/// **Not by substituting <c>e^(Stirling(f))</c> for the factorial**, which is the
/// obvious move and was measured to be much worse. It puts an <c>e</c> to a large
/// exponent into the expression, the machinery evaluates that constant to a
/// hundred-digit decimal, and everything downstream carries it:
/// <c>lim x->+oo (x!/e^x)^(1/x)</c> went from half a second to over a minute, on an
/// expression <see cref="StirlingExponent"/> already answers. Going through the
/// logarithm keeps the only <c>e</c> in the final answer.
/// <para/>
/// The guard is <see cref="PowerItAppearsTo"/>: it is the power of the factorial the
/// expression depends on, which is exactly the coefficient <c>ln(f!)</c> carries in
/// <c>ln H</c>, so the dropped <c>1/(12f)</c> has to vanish against it as everywhere
/// else. <c>(x!)^x</c> gives <c>x</c>, and <c>x/(12x)</c> does not vanish.
/// </remarks>
private static Entity? StirlingByItsOwnLogarithm(Entity expr, Variable x, Entity dest)
{
var factorials = DivergingFactorials(expr, x, dest);
if (factorials.Count == 0)
return null;
foreach (var factorial in factorials)
{
// The power the expression depends on the factorial through is the coefficient
// the dropped 1/(12f) arrives with, once the whole thing is read through its
// logarithm -- so it is the same guard as everywhere else, and it is refused
// where it does not vanish.
if (PowerItAppearsTo(expr, factorial, x) is not { } power || power == 0)
return null;
if (EvalAssumingContinuous(((Entity)power / factorial.Argument).Limit(x, dest)) != 0)
return null;
}
return LogarithmExpanded(expr, x, dest);
}
/// <summary>
/// <c>ln(antilogarithm)</c> taken apart over products, quotients and powers, with
/// Stirling's expansion written for the logarithm of a diverging factorial.
/// </summary>
private static Entity LogarithmExpanded(Entity antilogarithm, Variable x, Entity dest)
=> antilogarithm switch
{
Factorialf(var argument)
when EvalAssumingContinuous(argument.Limit(x, dest)) == Real.PositiveInfinity
=> StirlingSeries(argument),
Mulf(var a, var b) => LogarithmExpanded(a, x, dest) + LogarithmExpanded(b, x, dest),
Divf(var a, var b) => LogarithmExpanded(a, x, dest) - LogarithmExpanded(b, x, dest),
Powf(var b, var e) when !e.ContainsNode(x) || b.ContainsNode(x)
=> e * LogarithmExpanded(b, x, dest),
_ => MathS.Ln(antilogarithm)
};
/// <summary>
/// How deep the rewriting of one power into another may go. The exponent it asks about
/// is a limit in its own right and may hold a power of the same shape, so without a
/// bound the work would multiply.
/// </summary>
private const int MaxIndeterminatePowerDepth = 3;
[ThreadStatic] private static int indeterminatePowerDepth;
/// <summary>
/// Whether a limit's value is infinite: a real infinity anywhere inside it, or a complex
/// number with an infinite part, which is what <c>i * abs(x)</c> tends to and which
/// used to count as finite for being neither <c>+oo</c> nor <c>-oo</c> -- so
/// <c>i * abs(x) / x</c> was never read as oo/oo and l'Hopital's rule never saw it.
/// https://github.com/asc-community/AngouriMath/issues/1186
/// </summary>
private static bool IsInfiniteNode(Entity expr)
=> expr.ContainsNode("+oo") || expr.ContainsNode("-oo")
|| expr.Nodes.Any(node => node is Complex { IsFinite: false, IsNaN: false });
/// <summary>
/// Whether a limit's value is infinite and was decided to be: <see cref="IsInfiniteNode"/>,
/// but never for a value still holding a limit nobody could take.
/// </summary>
/// <remarks>
/// That limit is a question rather than a value, and the destination it carries is not
/// what it tends to: <c>limit(sin(u), x, +oo)</c> holds a <c>+oo</c> and says nothing
/// about diverging. l'Hopital's rule read sin(u) / cos(u) with both limits undecided as
/// oo/oo, differentiated it, and answered lim x->0- tan(x^2 + x - 1) with
/// -cos(-1) / sin(-1), 0.642, where it is tan(-1), -1.557. The rule is only true of the
/// forms it names, so it asks this.
/// <para/>
/// <see cref="IsInfiniteNode"/> is kept as it was for the rewrites that ask it whether
/// they are worth trying, which are equalities wherever they apply: f^g as e^(g ln f)
/// holds whatever f tends to, and an undecided base is exactly where it is worth asking.
/// </remarks>
private static bool DivergesDecidedly(Entity expr)
=> !HoldsAnUndecidedLimit(expr) && IsInfiniteNode(expr);
private static bool HoldsAnUndecidedLimit(Entity expr)
=> expr.Nodes.Any(node => node is Limitf);
/// <summary>
/// Whether what the machinery handed back is an indeterminate form rather than a value:
/// <c>0 / abs(0)</c>, <c>(+oo * 0)^2</c> -- a shape assembled out of the parts' limits
/// that evaluates to NaN without any part of it being NaN. NaN is the claim that there
/// is no limit, and a form the descent could not read is not that claim; it is the
/// descent saying nothing. A NaN that was decided -- <c>sin(x)</c> at <c>+oo</c>, and
/// <c>2 * sin(x)</c> with it -- carries the NaN node itself and is kept.
/// </summary>
/// <remarks>
/// Asked where the answer is made and nowhere inside: internally the form's NaN is
/// what stops every caller from searching further, and withholding it there let
/// <c>(sin(x) - x) / x^3</c> at 0 run for minutes.
/// https://github.com/asc-community/AngouriMath/issues/1186
/// </remarks>
internal static bool IsAnIndeterminateForm(Entity expr)
=> expr.Evaled == MathS.NaN && !expr.Nodes.Any(node => node == MathS.NaN);
/// <summary>
/// Whether a limit is being taken on behalf of another: the machinery asks for the
/// limits of its own parts through the same public entry point a caller uses, and an
/// answer withheld from those is a stop signal withheld from the search.
/// </summary>
internal static bool ReadingAnApproach => approachDepth > 0;
/// <summary>
/// Whether a power assembled out of the limits of its base and its exponent is an
/// indeterminate <em>form</em> that this library's arithmetic nonetheless answers with
/// a value, so that reading the value off would answer the limit wrongly.
/// </summary>
/// <remarks>
/// Substituting each part's own limit into a node and reading the result off is right
/// wherever the arithmetic is continuous there, and an indeterminate form is exactly
/// where it is not. Nearly all of them are already declined without any of this,
/// because they evaluate to NaN and every caller treats NaN as "no limit":
/// <c>0 * oo</c>, <c>oo - oo</c>, <c>oo / oo</c> and -- the one that matters here --
/// <c>0^0</c>. That last is why <c>lim x->0 x^x</c> is NaN, which this library means
/// deliberately and pins in <c>LimitTest.TestNoLimit</c>, so <c>0^0</c> is **not**
/// listed here: declining it would turn a considered "does not exist" into "not
/// settled".
/// <para/>
/// The gap is the two forms whose arithmetic gives 1 rather than NaN. <c>oo^0</c> and
/// <c>1^oo</c> are each the shape of limits with different values -- <c>(1 + 1/x)^x</c>
/// is <c>e</c> and <c>1^x</c> is 1, both of them <c>1^oo</c> -- and a limit that
/// assembled one of them read that 1 off as its answer:
/// <c>lim x->+oo (x!)^(1/x)</c> came back 1 where it is +oo.
/// <para/>
/// This says nothing about what the expression <c>(+oo)^0</c> evaluates to on its own.
/// That is a question of convention, on which this library agrees with SymPy and with
/// IEEE 754's <c>pow</c> in answering 1, and it is left exactly as it was.
/// <a href="https://github.com/asc-community/AngouriMath/issues/754">#754</a>
/// </remarks>
internal static bool IsIndeterminatePowerForm(Entity @base, Entity exponent)
{
var baseValue = EvalAssumingContinuous(@base);
var exponentValue = EvalAssumingContinuous(exponent);
if (exponentValue == 0)
return IsInfiniteNode(baseValue);
return baseValue == 1 && IsInfiniteNode(exponentValue);
}
/// <summary>
/// Whether an expression that a destination has already been substituted into holds an
/// indeterminate power form anywhere in it, in which case its value is not the limit.
/// </summary>
internal static bool HoldsAnIndeterminatePowerForm(Entity expr)
=> expr.Nodes.Any(node => node is Powf(var @base, var exponent)
&& IsIndeterminatePowerForm(@base, exponent));
/// <summary>
/// Whether <paramref name="argument"/>, a logarithm's or the base of a power, tends to
/// <paramref name="limit"/> on the negative real line, where the logarithm has its cut, and
/// is not known to arrive there along the real line.
/// </summary>
/// <remarks>
/// The principal logarithm is continuous on its cut from above only. Its value there,
/// <c>ln(-1) = i pi</c>, is the limit along the line and from above, and from below the limit
/// is <c>-i pi</c>. So a limit read off a logarithm of an argument's limit is that limit only
/// where the argument does not come from below: <c>x^x</c> tends to -1 from below as x comes
/// down to -1, and <c>limitright(ln(x^x), x, -1)</c> answered <c>i pi</c>. A power to an
/// exponent that is not whole is <c>e^(exponent * ln(base))</c> and has the same cut. Which
/// side an argument off the real line comes from is not decided here, so a limit there is
/// declined, including one from above, whose answer was right.
/// <a href="https://github.com/asc-community/AngouriMath/issues/2266">#2266</a>
/// </remarks>
internal static bool ArrivesOnTheCutOffTheRealLine(Entity argument, Entity? limit, Variable x, Entity dest)
=> argument.ContainsNode(x)
&& limit?.Evaled is Real { IsFinite: true, IsNegative: true }
&& !IsRealOnTheApproach(argument, x, dest);
/// <summary>
/// Whether a node of an expression that is about to be read at <paramref name="dest"/> is a
/// logarithm or a power whose argument arrives on the cut off the real line, by
/// <see cref="ArrivesOnTheCutOffTheRealLine"/>, with the argument's value at the destination
/// as its limit. A power to an exponent whose value there is whole is continuous across the
/// cut, where each of its values is reached from both sides.
/// </summary>
internal static bool TakesItsValueOnACut(Entity node, Variable x, Entity dest)
{
return node switch
{
Logf(var @base, var antilogarithm) => OnTheCut(@base) || OnTheCut(antilogarithm),
Powf(var @base, var exponent) => exponent.Substitute(x, dest).Evaled is not Integer && OnTheCut(@base),
// The arctangent's cut is the imaginary axis past i and -i, which no argument real on
// the approach reaches, and its value there is the limit from one side only:
// arctan(log(2, x)) at -1+ has its argument arriving at i pi / ln(2) from the left
// half-plane, and tends to -pi/2 + 0.224i, where the value there is pi/2 + 0.224i.
Arctanf(var argument) => argument.ContainsNode(x)
&& argument.Substitute(x, dest).Evaled is Complex { RealPart.IsZero: true, ImaginaryPart: var imaginary }
&& imaginary.EDecimal.Abs().CompareTo(PeterO.Numbers.EDecimal.One) > 0,
_ => false
};
bool OnTheCut(Entity argument) => ArrivesOnTheCutOffTheRealLine(argument, argument.Substitute(x, dest), x, dest);
}
/// <summary>
/// Whether <paramref name="expr"/> is real as <paramref name="x"/> runs along the real line to
/// <paramref name="dest"/>, decided structurally, as <see cref="IsRealAlong"/> is. A power's
/// base and a logarithm's argument count as positive where their values at the destination
/// are, which they then are near it. Anything else is
/// <see cref="TreeAnalyzer.IsRealValued"/>'s, and unlisted is not real, which costs
/// coverage and never correctness.
/// </summary>
private static bool IsRealOnTheApproach(Entity expr, Variable x, Entity dest)
{
if (dest.Evaled is not Real)
return false;
if (!expr.ContainsNode(x))
return expr.Evaled is Real { IsFinite: true };
return expr switch
{
Variable variable => variable == x,
Sumf(var augend, var addend) => Along(augend) && Along(addend),
Minusf(var minuend, var subtrahend) => Along(minuend) && Along(subtrahend),
Mulf(var multiplier, var multiplicand) => Along(multiplier) && Along(multiplicand),
Divf(var dividend, var divisor) => Along(dividend) && Along(divisor),
Powf(var @base, Integer) => Along(@base),
Powf(var @base, var exponent) => Along(@base) && Along(exponent) && PositiveThere(@base),
Logf(var @base, var antilogarithm) => Along(@base) && Along(antilogarithm)
&& PositiveThere(@base) && PositiveThere(antilogarithm),
_ => TreeAnalyzer.IsRealValued(expr, x)
};
bool Along(Entity part) => IsRealOnTheApproach(part, x, dest);
bool PositiveThere(Entity part) => part.Substitute(x, dest).Evaled is Real { IsPositive: true };
}
/// <summary>
/// Whether the exponent grows without bound, which is all the second remarkable
/// limit needs.
/// </summary>
/// <remarks>
/// Asking only for the two-sided limit is not enough: at <c>x -> 0</c> the
/// exponent <c>1/x</c> tends to -oo on the left and +oo on the right, so the
/// two-sided limit does not exist even though the magnitude diverges. That made
/// <c>lim x->0 (1 + x)^(1/x)</c> answer 1 rather than e. Both one-sided
/// limits diverging is enough, because the rewrite below only uses the product
/// <c>g(x) * (f(x) - 1)</c>, which is well defined from either side.
/// </remarks>
private static bool DivergesInMagnitude(Entity power, Variable x, Entity dest)
{
if (IsInfiniteNode(power.Limit(x, dest)))
return true;
// Only worth asking one side at a time where there are two sides to ask about.
// Approaching an infinite destination there is only one, so the two further
// limits would be wasted work and would not mean anything either.
if (IsInfiniteNode(dest))
return false;
return IsInfiniteNode(power.Limit(x, dest, ApproachFrom.Left))
&& IsInfiniteNode(power.Limit(x, dest, ApproachFrom.Right));
}
private static bool IsFiniteNode(Entity expr)
=> !HoldsAnUndecidedLimit(expr) && !IsInfiniteNode(expr) && expr != MathS.NaN;
/// <summary>
/// What an inverse trigonometric function tends to where its argument grows without
/// bound, or <see langword="null"/> where the argument does not diverge or the function
/// is not one this has a reading for.
/// </summary>