forked from thomas-xin/Miza
-
Notifications
You must be signed in to change notification settings - Fork 0
/
smath.py
2739 lines (2407 loc) · 73.5 KB
/
smath.py
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
"""
Adds many useful math-related functions.
"""
import os, sys, asyncio, threading, subprocess, psutil, traceback, time, datetime
import ctypes, collections, ast, copy, pickle
import random, math, cmath, fractions, mpmath, sympy, shlex, numpy, colorsys, re
import urllib.request, urllib.parse
from scipy import interpolate, special, signal
from dateutil import parser as tparser
from sympy.parsing.sympy_parser import parse_expr
from itertools import repeat
if hasattr(asyncio, "create_task"):
create_task = asyncio.create_task
else:
create_task = asyncio.ensure_future
loop = lambda x: repeat(None, x)
CalledProcessError = subprocess.CalledProcessError
Process = psutil.Process()
urlParse = urllib.parse.quote
np = numpy
array = numpy.array
deque = collections.deque
random.seed(random.random() + time.time() % 1)
mp = mpmath.mp
mp.dps = 64
math.round = round
mpf = mpmath.mpf
mpc = mpmath.mpc
Mat = mat = matrix = mpmath.matrix
inf = math.inf
nan = math.nan
i = I = j = J = 1j
pi = mp.pi
E = e = mp.e
c = 299792458
lP = 1.61625518e-35
mP = 2.17643524e-8
tP = 5.39124760e-44
h = 6.62607015e-34
G = 6.6743015e-11
g = 9.80665
tau = pi * 2
d2r = mp.degree
phi = mp.phi
euler = mp.euler
twinprime = mp.twinprime
Function = sympy.Function
Symbol = sympy.Symbol
factorize = factorint = primeFactors = sympy.ntheory.factorint
mobius = sympy.ntheory.mobius
TRUE, FALSE = True, False
true, false = True, False
def nop(*args):
pass
def shuffle(it):
if type(it) is list:
random.shuffle(it)
return it
elif type(it) is tuple:
it = list(it)
random.shuffle(it)
return it
elif type(it) is dict:
ir = sorted(it, key=lambda x: random.random())
new = {}
for i in ir:
new[i] = it[i]
it.clear()
it.update(new)
return it
elif type(it) is deque:
it = list(it)
random.shuffle(it)
return deque(it)
elif isinstance(it, hlist):
temp = it.shuffle()
it.data = temp.data
it.offs = temp.offs
del temp
return it
else:
try:
it = list(it)
random.shuffle(it)
return it
except TypeError:
raise TypeError("Shuffling " + type(it) + " is not supported.")
def reverse(it):
if type(it) is list:
return list(reversed(it))
elif type(it) is tuple:
return list(reversed(it))
elif type(it) is dict:
ir = tuple(reversed(it))
new = {}
for i in ir:
new[i] = it[i]
it.clear()
it.update(new)
return it
elif type(it) is deque:
return deque(reversed(it))
elif isinstance(it, hlist):
temp = it.reverse()
it.data = temp.data
it.offs = temp.offs
del temp
return it
else:
try:
return list(reversed(it))
except TypeError:
raise TypeError("Shuffling " + type(it) + " is not supported.")
def sort(it, key=lambda x: x, reverse=False):
if type(it) is list:
it.sort(key=key, reverse=reverse)
return it
elif type(it) is tuple:
it = sorted(it, key=key, reverse=reverse)
return it
elif type(it) is dict:
ir = sorted(it, key=key, reverse=reverse)
new = {}
for i in ir:
new[i] = it[i]
it.clear()
it.update(new)
return it
elif type(it) is deque:
it = sorted(it, key=key, reverse=reverse)
return deque(it)
elif isinstance(it, hlist):
it = hlist(sorted(it, key=key, reverse=reverse))
return it
else:
try:
it = list(it)
it.sort(key=key, reverse=reverse)
return it
except TypeError:
raise TypeError("Sorting " + type(it) + " is not supported.")
phase = cmath.phase
sin = mpmath.sin
cos = mpmath.cos
tan = mpmath.tan
sec = mpmath.sec
csc = mpmath.csc
cot = mpmath.cot
sinh = mpmath.sinh
cosh = mpmath.cosh
tanh = mpmath.tanh
sech = mpmath.sech
csch = mpmath.csch
coth = mpmath.coth
asin = mpmath.asin
acos = mpmath.acos
atan = mpmath.atan
asec = mpmath.asec
acsc = mpmath.acsc
acot = mpmath.acot
asinh = mpmath.asinh
acosh = mpmath.acosh
atanh = mpmath.atanh
asech = mpmath.asech
acsch = mpmath.acsch
acoth = mpmath.acoth
sinc = mpmath.sinc
atan2 = mpmath.atan2
ei = mpmath.ei
e1 = mpmath.e1
en = mpmath.expint
li = mpmath.li
si = mpmath.si
ci = mpmath.ci
shi = mpmath.shi
chi = mpmath.chi
erf = mpmath.erf
erfc = mpmath.erfc
erfi = mpmath.erfi
aerf = mpmath.erfinv
npdf = mpmath.npdf
ncdf = mpmath.ncdf
fac = factorial = mpmath.fac
fib = fibonacci = mpmath.fib
trib = tribonacci = sympy.tribonacci
luc = lucas = sympy.lucas
harm = harmonic = sympy.harmonic
ber = bernoulli = mpmath.bernoulli
eul = eulernum = mpmath.eulernum
sqrt = mpmath.sqrt
hypot = mpmath.hypot
cbrt = mpmath.cbrt
root = mpmath.root
exp = mpmath.exp
expi = expj = mpmath.expj
log = mpmath.log
ln = mpmath.ln
frac = sympy.frac
def isqrt(x):
x = int(x)
y = (x << 2) // 3
b = y.bit_length()
a = b >> 1
if b & 1:
c = 1 << a
d = (c + (x >> a)) >> 1
else:
c = (3 << a) >> 2
d = (c + (y >> a)) >> 1
if c != d:
c = d
d = (c + x // c) >> 1
while d < c:
c = d
d = (c + x // c) >> 1
return c
def round(x, y=None):
try:
if isValid(x):
try:
if x == int(x):
return int(x)
if y is None:
return int(math.round(x))
except:
pass
return roundMin(math.round(x, y))
else:
return x
except:
if type(x) is complex:
return round(x.real, y) + round(x.imag, y) * 1j
try:
return math.round(x)
except:
return x
def ceil(x):
try:
return math.ceil(x)
except:
if type(x) is complex:
return ceil(x.real) + ceil(x.imag) * 1j
try:
return math.ceil(x)
except:
return x
def floor(x):
try:
return math.floor(x)
except:
if type(x) is complex:
return floor(x.real) + floor(x.imag) * 1j
try:
return math.floor(x)
except:
return x
def trunc(x):
try:
return math.trunc(x)
except:
if type(x) is complex:
return trunc(x.real) + trunc(x.imag) * 1j
try:
return math.trunc(x)
except:
return x
def sqr(x):
return ((sin(x) >= 0) << 1) - 1
def saw(x):
return (x / pi + 1) % 2 - 1
def tri(x):
return (abs((0.5 - x / pi) % 2 - 1)) * 2 - 1
def sgn(x):
return (((x > 0) << 1) - 1) * (x != 0)
def frand(x=1, y=0):
return (random.random() * max(x, y) / mpf(random.random())) % x + y
def xrand(x, y=None, z=0):
if y == None:
y = 0
if x == y:
return x
return random.randint(floor(min(x, y)), ceil(max(x, y)) - 1) + z
def rrand(x=1, y=0):
return frand(x) ** (1 - y)
def modularInv(a, b):
if b == 0:
return (1, a)
a %= b
x = 0
y = 1
while a:
d = divmod(b, a)
a, b = d[1], a
x, y = y, x - (d[0]) * y
return (x, 1)
def pisanoPeriod(x):
a, b = 0, 1
for i in range(0, x * x):
a, b = b, (a + b) % x
if a == 0 and b == 1:
return i + 1
def jacobi(a, n):
if a == 0 or n < 0:
return 0
x = 1
if a < 0:
a = -a
if n & 3 == 3:
x = -x
if a == 1:
return x
while a:
if a < 0:
a = -a
if n & 3 == 3:
x = -x
while not a & 1:
a >>= 1
if n & 7 == 3 or n & 7 == 5:
x = -x
a, n = n, a
if a & 3 == 3 and n & 3 == 3:
x = -x
a %= n
if a > n >> 1:
a -= n
if n == 1:
return x
return 0
def next6np(start=0):
if start <= 2:
yield 2
if start <= 3:
yield 3
x = start - start % 6 + 6
if x > 6 and x - start >= 5:
yield x - 5
while True:
yield x - 1
yield x + 1
x += 6
def isPrime(n):
def divisibility(n):
t = min(n, 2 + ceil(log(n) ** 2))
g = next6np()
while True:
p = next(g)
if p >= t:
break
if n % p == 0:
return False
return True
def fermat(n):
t = min(n, 2 + ceil(log(n)))
g = next6np()
while True:
p = next(g)
if p >= t:
break
if pow(p, n - 1, n) != 1:
return False
return True
def miller(n):
d = n - 1
while d & 1 == 0:
d >>= 1
t = min(n, 2 + ceil(log(n)))
g = next6np()
while True:
p = next(g)
if p >= t:
break
x = pow(p, d, n)
if x == 1 or x == n - 1:
continue
while n != d + 1:
x = (x * x) % n
d <<= 1
if x == 1:
return False
if x == n - 1:
break
if n == d + 1:
return False
return True
def solovoyStrassen(n):
t = min(n, 2 + ceil(log(n)))
g = next6np()
while True:
p = next(g)
if p >= t:
break
j = (n + jacobi(p, n)) % n
if j == 0:
return False
m = pow(p, (n - 1) >> 1, n)
if m != j:
return False
return True
i = int(n)
if n == i:
n = i
if n < 2:
return False
if n <= 3:
return True
t = n % 6
if t != 1 and t != 5:
return False
if not divisibility(n):
return False
if not fermat(n):
return False
if not miller(n):
return False
if not solovoyStrassen(n):
return False
return True
return None
def generatePrimes(a=2, b=inf, c=1):
primes = hlist()
a = round(a)
b = round(b)
if b is None:
a, b = 0, a
if a > b:
a, b = b, a
a = max(1, a)
g = next6np(a)
while c:
p = next(g)
if p >= b:
break
if isPrime(p):
c -= 1
primes.append(p)
return primes
def getFactors(x):
f = factorize(x)
f.append(1)
s = {}
print(s)
def addDict(a, b, replace=True):
if replace:
r = a
else:
r = dict(a)
for k in b:
temp = a.get(k, None)
if temp is None:
r[k] = b[k]
continue
if type(temp) is dict or type(b[k]) is dict:
r[k] = addDict(b[k], temp, replace)
continue
r[k] = b[k] + temp
return r
def subDict(d, key):
output = dict(d)
try:
key[0]
except TypeError:
key = [key]
for k in key:
try:
output.pop(k)
except KeyError:
pass
return output
def roundMin(x):
if type(x) is not complex:
if isValid(x) and x == int(x):
return int(x)
else:
return x
else:
x = complex(x)
if x.imag == 0:
return roundMin(x.real)
else:
return roundMin(complex(x).real) + roundMin(complex(x).imag) * (1j)
def closeRound(n):
rounds = [0.125, 0.375, 0.625, 0.875, 0.25, 0.5, 0.75, 1 / 3, 2 / 3]
a = math.floor(n)
b = n % 1
c = round(b, 1)
for i in range(0, len(rounds)):
if abs(b - rounds[i]) < 0.02:
c = rounds[i]
return mpf(a + c)
def toFrac(num, limit=2147483647):
if num >= limit:
return [limit, 1]
if num <= 0:
return [1, limit]
num = mpf(num)
f = fractions.Fraction(num).limit_denominator(limit)
frac = [f.numerator, f.denominator]
if frac[0] == 0:
return [1, limit]
return frac
def gcd(x, y=1):
if y != 1:
while y > 0:
x, y = y, x % y
return x
return x
def lcm2(x, y=1):
if x != y:
x = abs(x)
y = abs(y)
i = True
if x != int(x):
i = False
x = toFrac(x)[0]
if y != int(y):
i = False
y = toFrac(y)[0]
if i:
return x * y // gcd(x, y)
else:
return toFrac(x / y)[0]
return x
def lcm(*x):
try:
while True:
x = [i for j in x for i in j]
except:
if 0 in x:
raise ValueError("Cannot find LCM of zero.")
while len(x) > 1:
x = [lcm2(x[i], x[-i - 1]) for i in range(ceil(len(x) / 2))]
return x[-1]
def lcmRange(x):
primes = generatePrimes(1, x, -1)
y = 1
for p in primes:
y *= p ** floor(log(x, p))
return y
def mean(*nums):
return roundMin(numpy.mean(numpy.array(nums)))
def pwr(x, power=2):
if x.real >= 0:
return roundMin(x ** power)
else:
return roundMin(-((-x) ** power))
def pulse(x, y=0.5):
p = y * tau
x *= 0.5 / len(x) * (x < p) + 0.5 / (1 - len(x)) * (x >= p)
return x
def isValid(x):
if type(x) is complex:
return not (cmath.isinf(x) or cmath.isnan(x))
try:
if type(x) is int:
return True
return x.is_finite()
except:
return math.isfinite(x)
def approach(x, y, z, threshold=0.125):
if z <= 1:
x = y
else:
x = (x * (z - 1) + y) / z
if abs(x - y) <= threshold / z:
x = y
return x
def xrange(a, b=None, c=None):
if b == None:
b = ceil(a.real)
a = 0
if c == None:
if a > b:
c = -1
else:
c = 1
return range(floor(a.real), ceil(b.real), c)
def romanNumerals(num, order=0):
num = int(num)
carry = 0
over = ""
sym = ""
output = ""
if num >= 4000:
carry = num // 1000
num %= 1000
over = romanNumerals(carry, order + 1)
while num >= 1000:
num -= 1000
output += "M"
if num >= 900:
num -= 900
output += "CM"
elif num >= 500:
num -= 500
output += "D"
elif num >= 400:
num -= 400
output += "CD"
while num >= 100:
num -= 100
output += "C"
if num >= 90:
num -= 90
output += "XC"
elif num >= 50:
num -= 50
output += "L"
elif num >= 40:
num -= 40
output += "XL"
while num >= 10:
num -= 10
output += "X"
if num >= 9:
num -= 9
output += "IX"
elif num >= 5:
num -= 5
output += "V"
elif num >= 4:
num -= 4
output += "IV"
while num >= 1:
num -= 1
output += "I"
if output != "":
if order == 1:
sym = "ᴍ"
elif order == 2:
sym = "ᴍᴹ"
return over + output + sym
def limStr(s, maxlen=10):
s = str(s)
over = (len(s) - maxlen) / 2
if over > 0:
half = len(s) / 2
s = s[: ceil(half - over - 1)] + ".." + s[ceil(half + over + 1) :]
return s
def expNum(num, maxlen=10, decimals=0):
if not isValid(num):
if num.real > 0:
return "inf"
elif num.real < 0:
return "-inf"
else:
return "NaN"
if type(num) is complex:
i = expNum(num.imag, maxlen // 2 - 1, decimals)
p = "+" if num.imag > 0 else ""
return expNum(num.real, ceil(maxlen / 2) - 1, decimals) + p + i + "i"
if num < 0:
n = "-"
num = -num
else:
n = ""
try:
numlen = floor(num.log10())
except:
numlen = floor(math.log10(max(0.001, num)))
if log(max(0.001, num), 10) <= maxlen - decimals:
return n + roundX(num, min(maxlen - numlen - 2 - len(n), decimals))
else:
if numlen > 0:
try:
loglen = floor(numlen.log10())
except:
loglen = floor(math.log10(numlen)) + len(n)
else:
loglen = 0
s = roundX(num / 10 ** numlen, maxlen - loglen - 5)[: max(1, maxlen - loglen - 2)]
if s[:3] == "10.":
s = "9." + "9" * (maxlen - loglen - 4)
return n + s + "e+" + str(numlen)
def roundX(num, prec):
if prec > 0:
s = str(round(num.real, round(prec)))
if "." in s:
while len(s) - s.index(".") <= prec:
s += "0"
else:
s += "." + "0" * prec
return s
else:
return str(round(num.real))
def verifyString(string):
if type(string) is list or type(string) is tuple:
return "".join([str(c) for c in string])
else:
return str(string)
def bytes2Hex(b):
o = ""
for a in b:
c = hex(a).upper()[2:]
if len(c) < 2:
c = "0" + c
o += c + " "
return o[:-1]
def hex2Bytes(h):
o = []
h = h.replace(" ", "").replace("\r", "").replace("\n", "")
for a in range(0, len(h), 2):
o.append(int(h[a : a + 2], 16))
return bytes(o)
def colourCalculation(a, offset=0):
return adjColour(colorsys.hsv_to_rgb((a / 1536) % 1, 1, 1), offset, 255)
def colour2Raw(c):
if len(c) == 3:
return (c[0] << 16) + (c[1] << 8) + c[2]
else:
return (c[0] << 16) + (c[1] << 8) + c[2] + (c[3] << 24)
def raw2Colour(x):
if x > 1 << 24:
return verifyColour(((x >> 16) & 255, (x >> 8) & 255, x & 255, (x >> 24) & 255))
else:
return verifyColour(((x >> 16) & 255, (x >> 8) & 255, x & 255))
def hex2Colour(h):
return verifyColour(hex2Bytes(h))
def luma(c):
return 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]
def verifyColour(c):
c = list(c)
for i in range(len(c)):
if c[i] > 255:
c[i] = 255
elif c[i] < 0:
c[i] = 0
c[i] = int(abs(c[i]))
return c
def fillColour(a):
if type(a) is complex:
a = a.real
if a > 255:
a = 255
elif a < 0:
a = 0
a = round(a)
return verifyColour([a, a, a])
def negColour(c, t=127):
i = luma(c)
if i > t:
return fillColour(0)
else:
return fillColour(255)
def invColour(c):
return [255 - i for i in c]
def adjColour(colour, brightness=0, intensity=1, hue=0, bits=0, scale=False):
if hue != 0:
h = list(colorsys.rgb_to_hsv(*(array(colour) / 255)))
c = adjColour(colorsys.hsv_to_rgb((h[0] + hue) % 1, h[1], h[2]), intensity=255)
else:
c = list(colour)
for i in range(len(c)):
c[i] = round(c[i] * intensity + brightness)
if scale:
for i in range(len(c)):
if c[i] > 255:
for j in range(len(c)):
if i != j:
c[j] += c[i] - 255
c[i] = 255
c = bitCrush(c, bits)
return verifyColour(c)
def bitCrush(dest, b=0, f=round):
try:
a = 1 << b
except:
a = 2 ** b
try:
len(dest)
dest = list(dest)
for i in range(len(dest)):
dest[i] = f(dest[i] / a) * a
except TypeError:
try:
dest = f(dest / a) * a
except:
raise
return dest
def listPermutation(dest):
order = [0 for i in range(len(dest))]
for i in range(len(dest)):
for j in range(i, len(dest)):
if dest[i] > dest[j]:
order[i] += 1
elif dest[i] < dest[j]:
order[j] += 1
return order
def multiVectorScalarOp(dest, operator):
expression = "a" + operator + "b"
function = eval("lambda a,b: " + expression)
output = []
for i in range(len(dest[0])):
s = 0
for j in range(len(dest)):
s = function(s, dest[j][i])
output.append(s)
return output
def vectorVectorOp(dest, source, operator):
expression = "dest[i]" + operator + "source[i]"
function = eval("lambda dest,source,i: " + expression)
for i in range(len(source)):
dest[i] = function(dest, source, i)
return dest
def vectorScalarOp(dest, source, operator):
expression = "dest[i]" + operator + str(source)
function = eval("lambda dest,i: " + expression)
for i in range(len(dest)):
dest[i] = function(dest, i)
return dest
def resizeVector(v, length, mode=5):
size = len(v)
new = round(length)
if new == size:
resized = v
elif mode == 0:
resized = numpy.array([v[round(i / new * size) % size] for i in range(new)])
elif mode <= 5 and mode == int(mode):
spl = interpolate.splrep(numpy.arange(1 + size), numpy.append(v, v[0]), k=int(min(size, mode)))
resized = numpy.array([interpolate.splev((i / new * size) % size, spl) for i in range(new)])
elif mode <= 5:
if math.floor(mode) == 0:
resized1 = resizeVector(v, new, 0)
else:
spl1 = interpolate.splrep(numpy.arange(1 + size), numpy.append(v, v[0]), k=floor(min(size, mode)))
resized1 = numpy.array([interpolate.splev((i / new * size) % size, spl1) for i in range(new)])
spl2 = interpolate.splrep(numpy.arange(1 + size), numpy.append(v, v[0]), k=ceil(min(size, mode)))
resized2 = numpy.array([interpolate.splev((i / new * size) % size, spl2) for i in range(new)])
resized = resized1 * (1 - mode % 1) + (mode % 1) * resized2
else:
resizing = []
for i in range(1, floor(mode)):
resizing.append(resizeVector(v, new, i / floor(mode) * 5))
resized = numpy.mean(resizing, 0)
return resized
def get(v, i, mode=5):
size = len(v)
i = i.real + i.imag * size
if i == int(i) or mode == 0:
return v[round(i) % size]
elif mode > 0 and mode < 1:
return get(v, i, 0) * (1 - mode) + mode * get(v, i, 1)
elif mode == 1:
return v[floor(i) % size] * (1 - i % 1) + v[ceil(i) % size] * (i % 1)
elif mode == int(mode):
return roundMin(interpolate.splev(i, interpolate.splrep(numpy.arange(1 + size), numpy.append(v, v[0]), k=int(min(size, mode)))))
else:
return get(v, i, floor(mode)) * (1 - mode % 1) + (mode % 1) * get(v, i, ceil(mode))
def product(*nums):
p = 1
for i in nums:
p *= i
return p
def dotProduct(*vects):
if len(vects) > 1:
return sum(product(*(array(v) for v in vects)))
else:
return sum((i ** 2 for i in vects[-1]))
def limitList(source, dest, direction=False):
for i in range(len(source)):
if direction:
if source[i] < dest[i]:
source[i] = dest[i]
else:
if source[i] > dest[i]:
source[i] = dest[i]
return source
def randomPolarCoord(x=1):
return polarCoords(frand(x), frand(tau))
def polarCoords(dist, angle, pos=None):
p = dist * array([math.cos(angle), math.sin(angle)])
if pos is None:
return p
return p + pos