-
Notifications
You must be signed in to change notification settings - Fork 2
/
ExtraMath.pas
885 lines (740 loc) · 21.5 KB
/
ExtraMath.pas
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
{
Copyright (c) Peter Karpov 2010 - 2017.
Usage of the works is permitted provided that this instrument is retained with
the works, so that any entity that uses the works is notified of this instrument.
DISCLAIMER: THE WORKS ARE WITHOUT WARRANTY.
}
{$IFDEF FPC} {$MODE DELPHI} {$ENDIF}
unit ExtraMath; /////////////////////////////////////////////////////////////////////
{
>> Version: 1.13
>> Description
Various mathematical routines. Part of InvLibs unit collection.
>> Author
Peter Karpov
Email : [email protected]
Homepage : inversed.ru
GitHub : inversed-ru
Twitter : @inversed_ru
>> ToDo
- Add Euler-Mascheroni constant and its exponentiated version
? Reciprocal versions of the constants (i or r prefix)
? Move machine epsilon constants to InvSys
>> References
- Rosser, J. B., Schoenfeld, L.
Approximate Formulas for Some Functions of Prime Numbers.
>> Changelog
1.13 : 2017.12.02 ~ Renamed the unit to ExtraMath
~ Renamed Blended to Blend and Blend to BlendTo
~ Renamed SumDivisors to SumOfDivisors
- InRange function (available in Math unit)
- mXau (duplicate of mTau)
~ FreePascal compatibility
1.12 : 2015.12.11 + GetDigits procedure
1.11 : 2015.06.20 * Bug in Modulo function for x = -M
1.10 : 2015.04.16 + SignedPower function
1.9 : 2015.03.09 + LCM function
+ Prime numbers section
+ CalcPrimes, CalcPrimesTo functions
+ Factorize procedure
+ PrimeCountUpper function
1.8 : 2014.10.10 + Totient function
+ SomDivisors function
+ Modular arithmetics section
1.7 : 2014.10.06 + Integer version of ClipCyclic
1.6 : 2014.09.24 + ClipInt function to allow disambiguous calls
1.5 : 2014.02.08 + RealModulo function
* Bug in Modulo function for x = 0, M < 0
* ClipCyclic function performance issue
1.4 : 2013.10.21 + UnitStep function
+ Median of 3 function
1.3 : 2013.06.13 ~ New constant naming convention
1.2 : 2013.04.29 + Digit function
+ InRange function
1.1 : 2013.02.06 + Geometric and logarithmic means
1.0 : 2013.02.03 ~ Reorganized into sections
+ (Multi)Factorial functions
+ Binomial coefficients
+ DivideByGCD procedure
~ Renamed Min3 function to Min
0.13 : 2012.10.03 + NPairs function
0.10 : 2012.03.18 + Blending
Notation: + added, - removed, * fixed, ~ changed
}
interface ///////////////////////////////////////////////////////////////////////////
uses
Arrays;
const
// Max relative rounding error aka machine epsilon for Single and Double types
SinglePrecision = 5.96e-8;
DoublePrecision = 1.11e-16;
RealPrecision = DoublePrecision;
var
mE, mGR, mTau : Real;
{-----------------------<< Integer sequences >>-------------------------------------}
// Factorial of n
function Fac(
n : Integer
) : Integer;
// Double factorial of n
function DoubleFac(
n : Integer
) : Integer;
// k-th multifactorial of n
function MultiFac(
n, k : Integer
) : Integer;
// The number of distinct pairs that can be selected from N objects
function NPairs(
N : Integer
) : Integer;
// Return i-th Fibonacci number. Fibonacci(0) = 0. Works for negative indices.
function Fibonacci(
i : Integer
) : Integer;
// Binomial coefficient C(n, k)
function Binomial(
n, k : Integer
) : Integer;
{-----------------------<< Prime numbers >>-----------------------------------------}
// Calculate first N Primes
procedure CalcPrimes(
var Primes : TIntArray;
N : Integer);
// Calculate first Primes up to MaxValue
procedure CalcPrimesTo(
var Primes : TIntArray;
MaxValue : Integer);
// Return a factorization of N into primes
procedure Factorize(
var PrimePowers : TIntArray;
N : Integer);
// Return an upper bound for the prime counting function giving number of primes <= N
function PrimeCountUpper(
N : Integer
) : Integer;
{-----------------------<< Integer Arithmetic >>------------------------------------}
// Return whether a is divisible by b or false in case of b = 0
function Divisible(
a, b : Integer
) : Boolean;
// Greatest common divisor of a and b
function GCD(
a, b : Integer
) : Integer;
// Least common multiple of a and b
function LCM(
a, b : Integer
) : Integer;
// Divide a and b by their greatest common divisor
procedure DivideByGCD(
var a, b : Integer);
// Euler's totient function: number of positive integers up to N coprime to it
function Totient(
N : Integer
) : Integer;
// Sum of p-th powers of divisors d of N, 1 < d < N
function SumOfDivisors(
N : Integer;
p : Integer
) : Integer;
// Return i-th digit of X in a given Base
function Digit(
x, i, Base : Integer;
Balanced : Boolean
) : Integer;
// Return the Digits of X in a given Base
procedure GetDigits(
var Digits : TIntArray;
x, Base : Integer;
Balanced : Boolean);
{-----------------------<< Modular Arithmetic >>------------------------------------}
// Return X modulo M. Result has the same sign as M.
function Modulo(
x, M : Integer
) : Integer;
// Return the minimal distance between a and b in a circular space of size M
function ModuloDistance(
a, b, M : Integer
) : Integer;
// Return X modulo M. Result has the same sign as M.
function RealModulo(
x, M : Real
) : Real;
{-----------------------<< Interpolation >>-----------------------------------------}
// Linearly interpolate from the Old (Alpha = 0) towards the New value (Alpha = 1)
procedure BlendTo(
var Old : Real;
New : Real;
Alpha : Real);
// Linearly interpolate between A (Alpha = 0) and B (Alpha = 1)
function Blend(
A, B, Alpha : Real
) : Real;
// Linearly interpolate between A (Alpha = 0) and B (Alpha = 1) in logarithmic scale
function LogBlend(
A, B, Alpha : Real
) : Real;
// Geometric mean of A and B
function GeoMean(
A, B : Real
) : Real;
// Logarithmic mean of A and B
function LogMean(
A, B : Real
) : Real;
{-----------------------<< Safe Functions >>----------------------------------------}
// Return Sqrt(x) or 0 if x < 0
function SafeSqrt(
x : Real
) : Real;
// Return Exp(x) or maximal real value on overflow
function SafeExp(
x : Real
) : Real;
// Return Ln(x) or the Default value if x <= 0
function SafeLn(
x,
Default : Real
) : Real;
// Return a / b or the Default value if b = 0
function SafeDiv(
a, b, Default : Real
) : Real;
{-----------------------<< Clipping >>----------------------------------------------}
// Clip x into [xMin, xMax] range
function Clip(
x, xMin, xMax : Real
) : Real;
overload;
function Clip(
x, xMin, xMax : Integer
) : Integer;
overload;
// Clip x into [xMin, xMax] range
function ClipInt(
x, xMin, xMax : Integer
) : Integer;
// Clip x into [MinX, MaxX] cyclic range
function ClipCyclic(
x, MinX, MaxX : Real
) : Real;
overload;
function ClipCyclic(
x, MinX, MaxX : Integer
) : Integer;
overload;
// Minimum of (a, b, c)
function Min(
a, b, c : Integer
) : Integer;
overload;
// Maximum of (a, b, c)
function Max(
a, b, c : Integer
) : Integer;
overload;
// Median of (a, b, c)
function Median(
a, b, c : Integer
) : Integer;
{-----------------------<< Misc real functions >>-----------------------------------}
// Sign-preserving power, returns Sign(x) * |x| ^ p
function SignedPower(
x, p : Real
) : Real;
// Cube root of x
function CubeRt(
x : Real
) : Real;
// Return 0, 1/2, 1 when x <, =, > 0 respectively
function UnitStep(
x : Real
) : Real;
implementation //////////////////////////////////////////////////////////////////////
uses
Math; // Min
{-----------------------<< Integer sequences >>-------------------------------------}
// k-th multifactorial of n
function MultiFac(
n, k : Integer
) : Integer;
var
i : Integer;
begin
i := n;
n := 1;
while i > 1 do
begin
n := n * i;
i := i - k;
end;
Result := n;
end;
// Factorial of n
function Fac(
n : Integer
) : Integer;
begin
Result := MultiFac(n, 1);
end;
// Double factorial of n
function DoubleFac(
n : Integer
) : Integer;
begin
Result := MultiFac(n, 2);
end;
// The number of distinct pairs that can be selected from N objects
function NPairs(
N : Integer
) : Integer;
begin
Result := (N * (N - 1)) div 2;
end;
// Return i-th Fibonacci number. Fibonacci(0) = 0. Works for negative indices.
function Fibonacci(
i : Integer
) : Integer;
begin
if i < 0 then
Result := (2 * (-i mod 2) - 1) * Fibonacci(-i)
else
Result := Round(IntPower(mGR, i) / Sqrt(5));
end;
// Binomial coefficient C(n, k)
function Binomial(
n, k : Integer
) : Integer;
var
i, g, r : Integer;
begin
k := Min(k, n - k);
if k < 0 then
r := 0
else
begin
r := 1;
for i := 1 to k do
begin
g := GCD(r, i);
r := (r div g) * (n - k + i) div (i div g);
end;
end;
Result := r;
end;
{-----------------------<< Prime numbers >>-----------------------------------------}
// Calculate Primes until MaxValue is reached or N numbers are found
procedure CalcPrimeNumbers(
var Primes : TIntArray;
N, MaxValue : Integer);
var
m, i, j : Integer;
IsPrime : Boolean;
begin
SetLength(Primes, 3);
Primes[0] := 2;
Primes[1] := 3;
Primes[2] := 5;
i := 3;
m := 7;
repeat
// Check primality
IsPrime := True;
j := 1;
repeat
if (m mod Primes[j]) = 0 then
begin
IsPrime := False;
{<---}break;
end;
Inc(j);
until Sqr(Primes[j]) > m;
// Add to the list if prime
if IsPrime then
begin
if i > (Length(Primes) - 1) then
SetLength(Primes, 2 * i);
Primes[i] := m;
Inc(i);
end;
Inc(m, 2);
until (i = N) or (m > MaxValue);
SetLength(Primes, i);
end;
// Calculate first N Primes
procedure CalcPrimes(
var Primes : TIntArray;
N : Integer);
begin
CalcPrimeNumbers(Primes, N, {MaxValue:} High(Integer));
end;
// Calculate first Primes up to MaxValue
procedure CalcPrimesTo(
var Primes : TIntArray;
MaxValue : Integer);
begin
CalcPrimeNumbers(Primes, {N:} 0, MaxValue);
end;
// Return an upper bound for the prime counting function giving number of primes <= N
function PrimeCountUpper(
N : Integer
) : Integer;
begin
Result := Floor( (N / Ln(N)) * ( 1 + 3 / (2 * Ln(N)) ) );
end;
// Return a factorization of N into primes
procedure Factorize(
var PrimePowers : TIntArray;
N : Integer);
var
Primes : TIntArray;
NPrimes, i : Integer;
begin
CalcPrimesTo(Primes, N);
NPrimes := Length(Primes);
InitArray(PrimePowers, NPrimes, 0);
for i := 0 to NPrimes - 1 do
while (N mod Primes[i]) = 0 do
begin
Inc(PrimePowers[i]);
N := N div Primes[i];
end;
end;
{-----------------------<< Integer arithmetic >>------------------------------------}
// Return whether a is divisible by b or false in case of b = 0
function Divisible(
a, b : Integer
) : Boolean;
begin
Result := (b <> 0) and ((a mod b) = 0);
end;
// Greatest common divisor of a and b
function GCD(
a, b : Integer
) : Integer;
var
t : Integer;
begin
while b <> 0 do
begin
t := b;
b := a mod b;
a := t;
end;
Result := a;
end;
// Least common multiple of a and b
function LCM(
a, b : Integer
) : Integer;
begin
Result := (a div GCD(a, b)) * b;
end;
// Divide a and b by their greatest common divisor
procedure DivideByGCD(
var a, b : Integer);
var
g : Integer;
begin
g := GCD(a, b);
a := a div g;
b := b div g;
end;
// Euler's totient function: number of positive integers up to N coprime to it
function Totient(
N : Integer
) : Integer;
var
i : Integer;
begin
Result := 1;
for i := 2 to N - 1 do
if GCD(i, N) = 1 then
Inc(Result);
end;
// Sum of p-th powers of divisors d of N, 1 < d < N
function SumOfDivisors(
N : Integer;
p : Integer
) : Integer;
var
i : Integer;
begin
Result := 0;
for i := 2 to N - 1 do
begin
if (N mod i) = 0 then
Result := Result + Round(IntPower(i, p));
end;
end;
// Return the least significant digit of X in a given Base, right shift X
function ExtractOneDigit(
var x : Integer;
Base : Integer;
Balanced : Boolean
) : Integer;
var
Shift : Integer;
begin
Shift := 0;
if Balanced then
begin
Assert(Base mod 2 = 1, 'Invalid base');
Shift := Base div 2;
end;
Result := Modulo(x + Shift, Base) - Shift;
x := (x - Result) div Base;
end;
// Return i-th digit of X in a given Base
function Digit(
x, i, Base : Integer;
Balanced : Boolean
) : Integer;
var
j : Integer;
begin
Result := 0;
for j := 0 to i do
Result := ExtractOneDigit(x, Base, Balanced);
end;
// Return the Digits of X in a given Base
procedure GetDigits(
var Digits : TIntArray;
x, Base : Integer;
Balanced : Boolean);
var
i : Integer;
const
MaxDigits = 32;
begin
i := 0;
SetLength(Digits, MaxDigits);
while x <> 0 do
begin
Digits[i] := ExtractOneDigit(x, Base, Balanced);
Inc(i);
end;
SetLength(Digits, i);
end;
{-----------------------<< Modular Arithmetic >>------------------------------------}
// Return X modulo M. Result has the same sign as M.
function Modulo(
x, M : Integer
) : Integer;
var
r : Integer;
begin
r := x mod M;
if ((x xor M) < 0) and (r <> 0) then
r := r + M;
Result := r;
end;
// Return the minimal distance between a and b in a circular space of size M
function ModuloDistance(
a, b, M : Integer
) : Integer;
begin
Result := Min( Modulo(a - b, M), Modulo(b - a, M) );
end;
// Return X modulo M. Result has the same sign as M.
function RealModulo(
x, M : Real
) : Real;
var
q : Integer;
begin
q := Floor(x / M);
Result := x - q * M;
end;
{-----------------------<< Interpolation >>-----------------------------------------}
// Linearly interpolate from the Old (Alpha = 0) towards the New value (Alpha = 1)
procedure BlendTo(
var Old : Real;
New : Real;
Alpha : Real);
begin
Old := Old + Alpha * (New - Old);
end;
// Linearly interpolate between A (Alpha = 0) and B (Alpha = 1)
function Blend(
A, B, Alpha : Real
) : Real;
begin
Result := A + Alpha * (B - A);
end;
// Linearly interpolate between A (Alpha = 0) and B (Alpha = 1) in logarithmic scale
function LogBlend(
A, B, Alpha : Real
) : Real;
begin
if A = 0 then
Result := 0 else
Result := A * Power(B / A, Alpha);
end;
// Geometric mean of A and B
function GeoMean(
A, B : Real
) : Real;
begin
Result := Sqrt(A * B);
end;
// Logarithmic mean of A and B
function LogMean(
A, B : Real
) : Real;
begin
if (A = 0) or (B = 0) then
Result := 0
else if A = B then
Result := B
else
Result := (A - B) / Ln(A / B);
end;
{-----------------------<< Safe functions >>----------------------------------------}
// Return Sqrt(x) or 0 if x < 0
function SafeSqrt(
x : Real
) : Real;
begin
if x < 0 then
Result := 0 else
Result := Sqrt(x);
end;
// Return Ln(x) or the Default value if x <= 0
function SafeLn(
x,
Default : Real
) : Real;
begin
if x > 0 then
Result := Ln(x) else
Result := Default;
end;
// Return Exp(x) or maximal real value on overflow
// #HACK should return infinity on overflow?
function SafeExp(
x : Real
) : Real;
begin
if x > Ln(MaxDouble) then
Result := MaxDouble else
Result := Exp(x);
end;
// Return a / b or the Default value if b = 0
function SafeDiv(
a, b, Default : Real
) : Real;
begin
if b = 0 then
Result := Default else
Result := a / b;
end;
{-----------------------<< Clipping >>----------------------------------------------}
// Clip x into [xMin, xMax] range
function Clip(
x, xMin, xMax : Real
) : Real;
overload;
begin
if x < xMin then
Result := xMin
else if x > xMax then
Result := xMax
else
Result := x;
end;
// Clip x into [xMin, xMax] range
function ClipInt(
x, xMin, xMax : Integer
) : Integer;
begin
Result := Round(Clip(0.0 + x, 0.0 + xMin, 0.0 + xMax));
end;
// Clip x into [xMin, xMax] range
function Clip(
x, xMin, xMax : Integer
) : Integer;
overload;
begin
Result := ClipInt(x, xMin, xMax);
end;
// Clip x into [MinX, MaxX] cyclic range
function ClipCyclic(
x, MinX, MaxX : Real
) : Real;
overload;
var
Range : Real;
begin
Range := MaxX - MinX;
Result := MinX + RealModulo(x - MinX, Range)
end;
function ClipCyclic(
x, MinX, MaxX : Integer
) : Integer;
overload;
var
Range : Integer;
begin
Range := MaxX - MinX + 1;
Result := MinX + Modulo(x - MinX, Range)
end;
// Minimum of (a, b, c)
function Min(
a, b, c : Integer
) : Integer;
overload;
begin
Result := a;
if b < Result then
Result := b;
if c < Result then
Result := c;
end;
// Maximum of (a, b, c)
function Max(
a, b, c : Integer
) : Integer;
overload;
begin
Result := a;
if b > Result then
Result := b;
if c > Result then
Result := c;
end;
// Median of (a, b, c)
function Median(
a, b, c : Integer
) : Integer;
begin
Result := a + b + c - Min(a, b, c) - Max(a, b, c);
end;
{-----------------------<< Misc real functions >>-----------------------------------}
// Sign-preserving power, returns Sign(x) * |x| ^ p
function SignedPower(
x, p : Real
) : Real;
begin
Result := Sign(x) * Power(Abs(x), p);
end;
// Cube root of x
function CubeRt(
x : Real
) : Real;
begin
Result := SignedPower(x, 1 / 3);
end;
// Return 0, 1/2, 1 when x <, =, > 0 respectively
function UnitStep(
x : Real
) : Real;
begin
Result := (1 + Sign(x)) / 2;
end;
initialization //////////////////////////////////////////////////////////////////////
mGR := (Sqrt(5) + 1) / 2;
mE := Exp(1);
mTau := 2 * Pi;
end.