forked from BelfrySCAD/BOSL2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
math.scad
1670 lines (1485 loc) · 64.2 KB
/
math.scad
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
//////////////////////////////////////////////////////////////////////
// LibFile: math.scad
// Assorted math functions, including linear interpolation, list operations (sums, mean, products),
// convolution, quantization, log2, hyperbolic trig functions, random numbers, derivatives,
// polynomials, and root finding.
// Includes:
// include <BOSL2/std.scad>
// FileGroup: Math
// FileSummary: Math on lists, special functions, quantization, random numbers, calculus, root finding
//
// FileFootnotes: STD=Included in std.scad
//////////////////////////////////////////////////////////////////////
// Section: Math Constants
// Constant: PHI
// Synopsis: The golden ratio φ (phi). Approximately 1.6180339887
// Topics: Constants, Math
// See Also: EPSILON, INF, NAN
// Description: The golden ratio φ (phi). Approximately 1.6180339887
PHI = (1+sqrt(5))/2;
// Constant: EPSILON
// Synopsis: A tiny value to compare floating point values. `1e-9`
// Topics: Constants, Math
// See Also: PHI, EPSILON, INF, NAN
// Description: A really small value useful in comparing floating point numbers. ie: abs(a-b)<EPSILON `1e-9`
EPSILON = 1e-9;
// Constant: INF
// Synopsis: The floating point value for Infinite.
// Topics: Constants, Math
// See Also: PHI, EPSILON, INF, NAN
// Description: The value `inf`, useful for comparisons.
INF = 1/0;
// Constant: NAN
// Synopsis: The floating point value for Not a Number.
// Topics: Constants, Math
// See Also: PHI, EPSILON, INF, NAN
// Description: The value `nan`, useful for comparisons.
NAN = acos(2);
// Section: Interpolation and Counting
// Function: count()
// Synopsis: Creates a list of incrementing numbers.
// Topics: Math, Indexing
// See Also: idx()
// Usage:
// list = count(n, [s], [step], [reverse]);
// Description:
// Creates a list of `n` numbers, starting at `s`, incrementing by `step` each time.
// You can also pass a list for n and then the length of the input list is used.
// Arguments:
// n = The length of the list of numbers to create, or a list to match the length of
// s = The starting value of the list of numbers.
// step = The amount to increment successive numbers in the list.
// reverse = Reverse the list. Default: false.
// Example:
// nl1 = count(5); // Returns: [0,1,2,3,4]
// nl2 = count(5,3); // Returns: [3,4,5,6,7]
// nl3 = count(4,3,2); // Returns: [3,5,7,9]
// nl4 = count(5,reverse=true); // Returns: [4,3,2,1,0]
// nl5 = count(5,3,reverse=true); // Returns: [7,6,5,4,3]
function count(n,s=0,step=1,reverse=false) = let(n=is_list(n) ? len(n) : n)
reverse? [for (i=[n-1:-1:0]) s+i*step]
: [for (i=[0:1:n-1]) s+i*step];
// Function: lerp()
// Synopsis: Linearly interpolates between two values.
// Topics: Interpolation, Math
// See Also: v_lookup(), lerpn()
// Usage:
// x = lerp(a, b, u);
// l = lerp(a, b, LIST);
// Description:
// Interpolate between two values or vectors.
// If `u` is given as a number, returns the single interpolated value.
// If `u` is 0.0, then the value of `a` is returned.
// If `u` is 1.0, then the value of `b` is returned.
// If `u` is a range, or list of numbers, returns a list of interpolated values.
// It is valid to use a `u` value outside the range 0 to 1. The result will be an extrapolation
// along the slope formed by `a` and `b`.
// Arguments:
// a = First value or vector.
// b = Second value or vector.
// u = The proportion from `a` to `b` to calculate. Standard range is 0.0 to 1.0, inclusive. If given as a list or range of values, returns a list of results.
// Example:
// x = lerp(0,20,0.3); // Returns: 6
// x = lerp(0,20,0.8); // Returns: 16
// x = lerp(0,20,-0.1); // Returns: -2
// x = lerp(0,20,1.1); // Returns: 22
// p = lerp([0,0],[20,10],0.25); // Returns [5,2.5]
// l = lerp(0,20,[0.4,0.6]); // Returns: [8,12]
// l = lerp(0,20,[0.25:0.25:0.75]); // Returns: [5,10,15]
// Example(2D):
// p1 = [-50,-20]; p2 = [50,30];
// stroke([p1,p2]);
// pts = lerp(p1, p2, [0:1/8:1]);
// // Points colored in ROYGBIV order.
// rainbow(pts) translate($item) circle(d=3,$fn=8);
function lerp(a,b,u) =
assert(same_shape(a,b), "Bad or inconsistent inputs to lerp")
is_finite(u)? (1-u)*a + u*b :
assert(is_finite(u) || is_vector(u) || valid_range(u), "Input u to lerp must be a number, vector, or valid range.")
[for (v = u) (1-v)*a + v*b ];
// Function: lerpn()
// Synopsis: Returns exactly `n` values, linearly interpolated between `a` and `b`.
// Topics: Interpolation, Math
// See Also: v_lookup(), lerp()
// Usage:
// x = lerpn(a, b, n);
// x = lerpn(a, b, n, [endpoint]);
// Description:
// Returns exactly `n` values, linearly interpolated between `a` and `b`.
// If `endpoint` is true, then the last value will exactly equal `b`.
// If `endpoint` is false, then the last value will be `a+(b-a)*(1-1/n)`.
// Arguments:
// a = First value or vector.
// b = Second value or vector.
// n = The number of values to return.
// endpoint = If true, the last value will be exactly `b`. If false, the last value will be one step less.
// Example:
// l = lerpn(-4,4,9); // Returns: [-4,-3,-2,-1,0,1,2,3,4]
// l = lerpn(-4,4,8,false); // Returns: [-4,-3,-2,-1,0,1,2,3]
// l = lerpn(0,1,6); // Returns: [0, 0.2, 0.4, 0.6, 0.8, 1]
// l = lerpn(0,1,5,false); // Returns: [0, 0.2, 0.4, 0.6, 0.8]
function lerpn(a,b,n,endpoint=true) =
assert(same_shape(a,b), "Bad or inconsistent inputs to lerpn")
assert(is_int(n))
assert(is_bool(endpoint))
let( d = n - (endpoint? 1 : 0) )
[for (i=[0:1:n-1]) let(u=i/d) (1-u)*a + u*b];
// Section: Miscellaneous Functions
// Function: sqr()
// Synopsis: Returns the square of the given value.
// Topics: Math
// See Also: hypot(), log2()
// Usage:
// x2 = sqr(x);
// Description:
// If given a number, returns the square of that number,
// If given a vector, returns the sum-of-squares/dot product of the vector elements.
// If given a matrix, returns the matrix multiplication of the matrix with itself.
// Example:
// sqr(3); // Returns: 9
// sqr(-4); // Returns: 16
// sqr([2,3,4]); // Returns: 29
// sqr([[1,2],[3,4]]); // Returns [[7,10],[15,22]]
function sqr(x) =
assert(is_finite(x) || is_vector(x) || is_matrix(x), "Input is not a number nor a list of numbers.")
x*x;
// Function: log2()
// Synopsis: Returns the log base 2 of the given value.
// Topics: Math
// See Also: hypot(), sqr()
// Usage:
// val = log2(x);
// Description:
// Returns the logarithm base 2 of the value given.
// Example:
// log2(0.125); // Returns: -3
// log2(16); // Returns: 4
// log2(256); // Returns: 8
function log2(x) =
assert( is_finite(x), "Input is not a number.")
ln(x)/ln(2);
// this may return NAN or INF; should it check x>0 ?
// Function: hypot()
// Synopsis: Returns the hypotenuse length of a 2D or 3D triangle.
// Topics: Math
// See Also: hypot(), sqr(), log2()
// Usage:
// l = hypot(x, y, [z]);
// Description:
// Calculate hypotenuse length of a 2D or 3D triangle.
// Arguments:
// x = Length on the X axis.
// y = Length on the Y axis.
// z = Length on the Z axis. Optional.
// Example:
// l = hypot(3,4); // Returns: 5
// l = hypot(3,4,5); // Returns: ~7.0710678119
function hypot(x,y,z=0) =
assert( is_vector([x,y,z]), "Improper number(s).")
norm([x,y,z]);
// Function: factorial()
// Synopsis: Returns the factorial of the given integer.
// Topics: Math
// See Also: hypot(), sqr(), log2()
// Usage:
// x = factorial(n, [d]);
// Description:
// Returns the factorial of the given integer value, or n!/d! if d is given.
// Arguments:
// n = The integer number to get the factorial of. (n!)
// d = If given, the returned value will be (n! / d!)
// Example:
// x = factorial(4); // Returns: 24
// y = factorial(6); // Returns: 720
// z = factorial(9); // Returns: 362880
function factorial(n,d=0) =
assert(is_int(n) && is_int(d) && n>=0 && d>=0, "Factorial is defined only for non negative integers")
assert(d<=n, "d cannot be larger than n")
product([1,for (i=[n:-1:d+1]) i]);
// Function: binomial()
// Synopsis: Returns the binomial coefficients of the integer `n`.
// Topics: Math
// See Also: hypot(), sqr(), log2(), factorial()
// Usage:
// x = binomial(n);
// Description:
// Returns the binomial coefficients of the integer `n`.
// Arguments:
// n = The integer to get the binomial coefficients of
// Example:
// x = binomial(3); // Returns: [1,3,3,1]
// y = binomial(4); // Returns: [1,4,6,4,1]
// z = binomial(6); // Returns: [1,6,15,20,15,6,1]
function binomial(n) =
assert( is_int(n) && n>0, "Input is not an integer greater than 0.")
[for( c = 1, i = 0;
i<=n;
c = c*(n-i)/(i+1), i = i+1
) c ] ;
// Function: binomial_coefficient()
// Synopsis: Returns the `k`-th binomial coefficient of the integer `n`.
// Topics: Math
// See Also: hypot(), sqr(), log2(), factorial()
// Usage:
// x = binomial_coefficient(n, k);
// Description:
// Returns the `k`-th binomial coefficient of the integer `n`.
// Arguments:
// n = The integer to get the binomial coefficient of
// k = The binomial coefficient index
// Example:
// x = binomial_coefficient(3,2); // Returns: 3
// y = binomial_coefficient(10,6); // Returns: 210
function binomial_coefficient(n,k) =
assert( is_int(n) && is_int(k), "Some input is not a number.")
k < 0 || k > n ? 0 :
k ==0 || k ==n ? 1 :
let( k = min(k, n-k),
b = [for( c = 1, i = 0;
i<=k;
c = c*(n-i)/(i+1), i = i+1
) c] )
b[len(b)-1];
// Function: gcd()
// Synopsis: Returns the Greatest Common Divisor/Factor of two integers.
// Topics: Math
// See Also: hypot(), sqr(), log2(), factorial(), binomial(), gcd(), lcm()
// Usage:
// x = gcd(a,b)
// Description:
// Computes the Greatest Common Divisor/Factor of `a` and `b`.
function gcd(a,b) =
assert(is_int(a) && is_int(b),"Arguments to gcd must be integers")
b==0 ? abs(a) : gcd(b,a % b);
// Computes lcm for two integers
function _lcm(a,b) =
assert(is_int(a) && is_int(b), "Invalid non-integer parameters to lcm")
assert(a!=0 && b!=0, "Arguments to lcm should not be zero")
abs(a*b) / gcd(a,b);
// Computes lcm for a list of values
function _lcmlist(a) =
len(a)==1 ? a[0] :
_lcmlist(concat(lcm(a[0],a[1]),list_tail(a,2)));
// Function: lcm()
// Synopsis: Returns the Least Common Multiple of two or more integers.
// Topics: Math
// See Also: hypot(), sqr(), log2(), factorial(), binomial(), gcd(), lcm()
// Usage:
// div = lcm(a, b);
// divs = lcm(list);
// Description:
// Computes the Least Common Multiple of the two arguments or a list of arguments. Inputs should
// be non-zero integers. The output is always a positive integer. It is an error to pass zero
// as an argument.
function lcm(a,b=[]) =
!is_list(a) && !is_list(b)
? _lcm(a,b)
: let( arglist = concat(force_list(a),force_list(b)) )
assert(len(arglist)>0, "Invalid call to lcm with empty list(s)")
_lcmlist(arglist);
// Function rational_approx()
// Usage:
// pq = rational_approx(x, maxq);
// Description:
// Finds the best rational approximation p/q to the number x so that q<=maxq. Returns
// the result as `[p,q]`. If the input is zero, then returns `[0,1]`.
// Example:
// pq1 = rational_approx(PI,10); // Returns: [22,7]
// pq2 = rational_approx(PI,10000); // Returns: [355, 113]
// pq3 = rational_approx(221/323,500); // Returns: [13,19]
// pq4 = rational_approx(0,50); // Returns: [0,1]
function rational_approx(x, maxq, cfrac=[], p, q) =
let(
next = floor(x),
fracpart = x-next,
cfrac = [each cfrac, next],
pq = _cfrac_to_pq(cfrac)
)
approx(fracpart,0) ? pq
: pq[1]>maxq ? [p,q]
: rational_approx(1/fracpart,maxq,cfrac, pq[0], pq[1]);
// Converts a continued fraction given as a list with leading integer term
// into a fraction in the form p / q, returning [p,q].
function _cfrac_to_pq(cfrac,p=0,q=1,ind) =
is_undef(ind) ? _cfrac_to_pq(cfrac,p,q,len(cfrac)-1)
: ind==0 ? [p+q*cfrac[0], q]
: _cfrac_to_pq(cfrac, q, cfrac[ind]*q+p, ind-1);
// Section: Hyperbolic Trigonometry
// Function: sinh()
// Synopsis: Returns the hyperbolic sine of the given value.
// Topics: Math, Trigonometry
// See Also: sinh(), cosh(), tanh(), asinh(), acosh(), atanh()
// Usage:
// a = sinh(x);
// Description: Takes a value `x`, and returns the hyperbolic sine of it.
function sinh(x) =
assert(is_finite(x), "The input must be a finite number.")
(exp(x)-exp(-x))/2;
// Function: cosh()
// Synopsis: Returns the hyperbolic cosine of the given value.
// Topics: Math, Trigonometry
// See Also: sinh(), cosh(), tanh(), asinh(), acosh(), atanh()
// Usage:
// a = cosh(x);
// Description: Takes a value `x`, and returns the hyperbolic cosine of it.
function cosh(x) =
assert(is_finite(x), "The input must be a finite number.")
(exp(x)+exp(-x))/2;
// Function: tanh()
// Synopsis: Returns the hyperbolic tangent of the given value.
// Topics: Math, Trigonometry
// See Also: sinh(), cosh(), tanh(), asinh(), acosh(), atanh()
// Usage:
// a = tanh(x);
// Description: Takes a value `x`, and returns the hyperbolic tangent of it.
function tanh(x) =
assert(is_finite(x), "The input must be a finite number.")
sinh(x)/cosh(x);
// Function: asinh()
// Synopsis: Returns the hyperbolic arc-sine of the given value.
// Topics: Math, Trigonometry
// See Also: sinh(), cosh(), tanh(), asinh(), acosh(), atanh()
// Usage:
// a = asinh(x);
// Description: Takes a value `x`, and returns the inverse hyperbolic sine of it.
function asinh(x) =
assert(is_finite(x), "The input must be a finite number.")
ln(x+sqrt(x*x+1));
// Function: acosh()
// Synopsis: Returns the hyperbolic arc-cosine of the given value.
// Topics: Math, Trigonometry
// See Also: sinh(), cosh(), tanh(), asinh(), acosh(), atanh()
// Usage:
// a = acosh(x);
// Description: Takes a value `x`, and returns the inverse hyperbolic cosine of it.
function acosh(x) =
assert(is_finite(x), "The input must be a finite number.")
ln(x+sqrt(x*x-1));
// Function: atanh()
// Synopsis: Returns the hyperbolic arc-tangent of the given value.
// Topics: Math, Trigonometry
// See Also: sinh(), cosh(), tanh(), asinh(), acosh(), atanh()
// Usage:
// a = atanh(x);
// Description: Takes a value `x`, and returns the inverse hyperbolic tangent of it.
function atanh(x) =
assert(is_finite(x), "The input must be a finite number.")
ln((1+x)/(1-x))/2;
// Section: Quantization
// Function: quant()
// Synopsis: Returns `x` quantized to the nearest integer multiple of `y`.
// Topics: Math, Quantization
// See Also: quant(), quantdn(), quantup()
// Usage:
// num = quant(x, y);
// Description:
// Quantize a value `x` to an integer multiple of `y`, rounding to the nearest multiple.
// The value of `y` does NOT have to be an integer. If `x` is a list, then every item
// in that list will be recursively quantized.
// Arguments:
// x = The value or list to quantize.
// y = Positive quantum to quantize to
// Example:
// a = quant(12,4); // Returns: 12
// b = quant(13,4); // Returns: 12
// c = quant(13.1,4); // Returns: 12
// d = quant(14,4); // Returns: 16
// e = quant(14.1,4); // Returns: 16
// f = quant(15,4); // Returns: 16
// g = quant(16,4); // Returns: 16
// h = quant(9,3); // Returns: 9
// i = quant(10,3); // Returns: 9
// j = quant(10.4,3); // Returns: 9
// k = quant(10.5,3); // Returns: 12
// l = quant(11,3); // Returns: 12
// m = quant(12,3); // Returns: 12
// n = quant(11,2.5); // Returns: 10
// o = quant(12,2.5); // Returns: 12.5
// p = quant([12,13,13.1,14,14.1,15,16],4); // Returns: [12,12,12,16,16,16,16]
// q = quant([9,10,10.4,10.5,11,12],3); // Returns: [9,9,9,12,12,12]
// r = quant([[9,10,10.4],[10.5,11,12]],3); // Returns: [[9,9,9],[12,12,12]]
function quant(x,y) =
assert( is_finite(y) && y>0, "The quantum `y` must be a positive value.")
is_num(x) ? round(x/y)*y
: _roundall(x/y)*y;
function _roundall(data) =
[for(x=data) is_list(x) ? _roundall(x) : round(x)];
// Function: quantdn()
// Synopsis: Returns `x` quantized down to an integer multiple of `y`.
// Topics: Math, Quantization
// See Also: quant(), quantdn(), quantup()
// Usage:
// num = quantdn(x, y);
// Description:
// Quantize a value `x` to an integer multiple of `y`, rounding down to the previous multiple.
// The value of `y` does NOT have to be an integer. If `x` is a list, then every item in that
// list will be recursively quantized down.
// Arguments:
// x = The value or list to quantize.
// y = Postive quantum to quantize to.
// Example:
// a = quantdn(12,4); // Returns: 12
// b = quantdn(13,4); // Returns: 12
// c = quantdn(13.1,4); // Returns: 12
// d = quantdn(14,4); // Returns: 12
// e = quantdn(14.1,4); // Returns: 12
// f = quantdn(15,4); // Returns: 12
// g = quantdn(16,4); // Returns: 16
// h = quantdn(9,3); // Returns: 9
// i = quantdn(10,3); // Returns: 9
// j = quantdn(10.4,3); // Returns: 9
// k = quantdn(10.5,3); // Returns: 9
// l = quantdn(11,3); // Returns: 9
// m = quantdn(12,3); // Returns: 12
// n = quantdn(11,2.5); // Returns: 10
// o = quantdn(12,2.5); // Returns: 10
// p = quantdn([12,13,13.1,14,14.1,15,16],4); // Returns: [12,12,12,12,12,12,16]
// q = quantdn([9,10,10.4,10.5,11,12],3); // Returns: [9,9,9,9,9,12]
// r = quantdn([[9,10,10.4],[10.5,11,12]],3); // Returns: [[9,9,9],[9,9,12]]
function quantdn(x,y) =
assert( is_finite(y) && y>0, "The quantum `y` must be a positive value.")
is_num(x) ? floor(x/y)*y
: _floorall(x/y)*y;
function _floorall(data) =
[for(x=data) is_list(x) ? _floorall(x) : floor(x)];
// Function: quantup()
// Synopsis: Returns `x` quantized uo to an integer multiple of `y`.
// Topics: Math, Quantization
// See Also: quant(), quantdn(), quantup()
// Usage:
// num = quantup(x, y);
// Description:
// Quantize a value `x` to an integer multiple of `y`, rounding up to the next multiple.
// The value of `y` does NOT have to be an integer. If `x` is a list, then every item in
// that list will be recursively quantized up.
// Arguments:
// x = The value or list to quantize.
// y = Positive quantum to quantize to.
// Example:
// a = quantup(12,4); // Returns: 12
// b = quantup(13,4); // Returns: 16
// c = quantup(13.1,4); // Returns: 16
// d = quantup(14,4); // Returns: 16
// e = quantup(14.1,4); // Returns: 16
// f = quantup(15,4); // Returns: 16
// g = quantup(16,4); // Returns: 16
// h = quantup(9,3); // Returns: 9
// i = quantup(10,3); // Returns: 12
// j = quantup(10.4,3); // Returns: 12
// k = quantup(10.5,3); // Returns: 12
// l = quantup(11,3); // Returns: 12
// m = quantup(12,3); // Returns: 12
// n = quantdn(11,2.5); // Returns: 12.5
// o = quantdn(12,2.5); // Returns: 12.5
// p = quantup([12,13,13.1,14,14.1,15,16],4); // Returns: [12,16,16,16,16,16,16]
// q = quantup([9,10,10.4,10.5,11,12],3); // Returns: [9,12,12,12,12,12]
// r = quantup([[9,10,10.4],[10.5,11,12]],3); // Returns: [[9,12,12],[12,12,12]]
function quantup(x,y) =
assert( is_finite(y) && y>0, "The quantum `y` must be a positive value.")
is_num(x) ? ceil(x/y)*y
: _ceilall(x/y)*y;
function _ceilall(data) =
[for(x=data) is_list(x) ? _ceilall(x) : ceil(x)];
// Section: Constraints and Modulos
// Function: constrain()
// Synopsis: Returns a value constrained between `minval` and `maxval`, inclusive.
// Topics: Math
// See Also: posmod(), modang()
// Usage:
// val = constrain(v, minval, maxval);
// Description:
// Constrains value to a range of values between minval and maxval, inclusive.
// Arguments:
// v = value to constrain.
// minval = minimum value to return, if out of range.
// maxval = maximum value to return, if out of range.
// Example:
// a = constrain(-5, -1, 1); // Returns: -1
// b = constrain(5, -1, 1); // Returns: 1
// c = constrain(0.3, -1, 1); // Returns: 0.3
// d = constrain(9.1, 0, 9); // Returns: 9
// e = constrain(-0.1, 0, 9); // Returns: 0
function constrain(v, minval, maxval) =
assert( is_finite(v+minval+maxval), "Input must be finite number(s).")
min(maxval, max(minval, v));
// Function: posmod()
// Synopsis: Returns the positive modulo of a value.
// Topics: Math
// See Also: constrain(), posmod(), modang()
// Usage:
// mod = posmod(x, m)
// Description:
// Returns the positive modulo `m` of `x`. Value returned will be in the range 0 ... `m`-1.
// Arguments:
// x = The value to constrain.
// m = Modulo value.
// Example:
// a = posmod(-700,360); // Returns: 340
// b = posmod(-270,360); // Returns: 90
// c = posmod(-120,360); // Returns: 240
// d = posmod(120,360); // Returns: 120
// e = posmod(270,360); // Returns: 270
// f = posmod(700,360); // Returns: 340
// g = posmod(3,2.5); // Returns: 0.5
function posmod(x,m) =
assert( is_finite(x) && is_finite(m) && !approx(m,0) , "Input must be finite numbers. The divisor cannot be zero.")
(x%m+m)%m;
// Function: modang()
// Synopsis: Returns an angle normalized to between -180º and 180º.
// Topics: Math
// See Also: constrain(), posmod(), modang()
// Usage:
// ang = modang(x);
// Description:
// Takes an angle in degrees and normalizes it to an equivalent angle value between -180 and 180.
// Example:
// a1 = modang(-700); // Returns: 20
// a2 = modang(-270); // Returns: 90
// a3 = modang(-120); // Returns: -120
// a4 = modang(120); // Returns: 120
// a5 = modang(270); // Returns: -90
// a6 = modang(700); // Returns: -20
function modang(x) =
assert( is_finite(x), "Input must be a finite number.")
let(xx = posmod(x,360)) xx<180? xx : xx-360;
// Section: Operations on Lists (Sums, Mean, Products)
// Function: sum()
// Synopsis: Returns the sum of a list of values.
// Topics: Math
// See Also: mean(), median(), product(), cumsum()
// Usage:
// x = sum(v, [dflt]);
// Description:
// Returns the sum of all entries in the given consistent list.
// If passed an array of vectors, returns the sum the vectors.
// If passed an array of matrices, returns the sum of the matrices.
// If passed an empty list, the value of `dflt` will be returned.
// Arguments:
// v = The list to get the sum of.
// dflt = The default value to return if `v` is an empty list. Default: 0
// Example:
// sum([1,2,3]); // returns 6.
// sum([[1,2,3], [3,4,5], [5,6,7]]); // returns [9, 12, 15]
function sum(v, dflt=0) =
v==[]? dflt :
assert(is_consistent(v), "Input to sum is non-numeric or inconsistent")
is_finite(v[0]) || is_vector(v[0]) ? [for(i=v) 1]*v :
_sum(v,v[0]*0);
function _sum(v,_total,_i=0) = _i>=len(v) ? _total : _sum(v,_total+v[_i], _i+1);
// Function: mean()
// Synopsis: Returns the mean value of a list of values.
// Topics: Math, Statistics
// See Also: sum(), mean(), median(), product()
// Usage:
// x = mean(v);
// Description:
// Returns the arithmetic mean/average of all entries in the given array.
// If passed a list of vectors, returns a vector of the mean of each part.
// Arguments:
// v = The list of values to get the mean of.
// Example:
// mean([2,3,4]); // returns 3.
// mean([[1,2,3], [3,4,5], [5,6,7]]); // returns [3, 4, 5]
function mean(v) =
assert(is_list(v) && len(v)>0, "Invalid list.")
sum(v)/len(v);
// Function: median()
// Synopsis: Returns the median value of a list of values.
// Topics: Math, Statistics
// See Also: sum(), mean(), median(), product()
// Usage:
// middle = median(v)
// Description:
// Returns the median of the given vector.
function median(v) =
assert(is_vector(v), "Input to median must be a vector")
len(v)%2 ? max( list_smallest(v, ceil(len(v)/2)) ) :
let( lowest = list_smallest(v, len(v)/2 + 1),
max = max(lowest),
imax = search(max,lowest,1),
max2 = max([for(i=idx(lowest)) if(i!=imax[0]) lowest[i] ])
)
(max+max2)/2;
// Function: deltas()
// Synopsis: Returns the deltas between a list of values.
// Topics: Math, Statistics
// See Also: sum(), mean(), median(), product()
// Usage:
// delts = deltas(v,[wrap]);
// Description:
// Returns a list with the deltas of adjacent entries in the given list, optionally wrapping back to the front.
// The list should be a consistent list of numeric components (numbers, vectors, matrix, etc).
// Given [a,b,c,d], returns [b-a,c-b,d-c].
// Arguments:
// v = The list to get the deltas of.
// wrap = If true, wrap back to the start from the end. ie: return the difference between the last and first items as the last delta. Default: false
// Example:
// deltas([2,5,9,17]); // returns [3,4,8].
// deltas([[1,2,3], [3,6,8], [4,8,11]]); // returns [[2,4,5], [1,2,3]]
function deltas(v, wrap=false) =
assert( is_consistent(v) && len(v)>1 , "Inconsistent list or with length<=1.")
[for (p=pair(v,wrap)) p[1]-p[0]] ;
// Function: cumsum()
// Synopsis: Returns the running cumulative sum of a list of values.
// Topics: Math, Statistics
// See Also: sum(), mean(), median(), product()
// Usage:
// sums = cumsum(v);
// Description:
// Returns a list where each item is the cumulative sum of all items up to and including the corresponding entry in the input list.
// If passed an array of vectors, returns a list of cumulative vectors sums.
// Arguments:
// v = The list to get the sum of.
// Example:
// cumsum([1,1,1]); // returns [1,2,3]
// cumsum([2,2,2]); // returns [2,4,6]
// cumsum([1,2,3]); // returns [1,3,6]
// cumsum([[1,2,3], [3,4,5], [5,6,7]]); // returns [[1,2,3], [4,6,8], [9,12,15]]
function cumsum(v) =
assert(is_consistent(v), "The input is not consistent." )
len(v)<=1 ? v :
_cumsum(v,_i=1,_acc=[v[0]]);
function _cumsum(v,_i=0,_acc=[]) =
_i>=len(v) ? _acc :
_cumsum( v, _i+1, [ each _acc, _acc[len(_acc)-1] + v[_i] ] );
// Function: product()
// Synopsis: Returns the multiplicative product of a list of values.
// Topics: Math, Statistics
// See Also: sum(), mean(), median(), product(), cumsum()
// Usage:
// x = product(v);
// Description:
// Returns the product of all entries in the given list.
// If passed a list of vectors of same dimension, returns a vector of products of each part.
// If passed a list of square matrices, returns the resulting product matrix.
// Arguments:
// v = The list to get the product of.
// Example:
// product([2,3,4]); // returns 24.
// product([[1,2,3], [3,4,5], [5,6,7]]); // returns [15, 48, 105]
function product(v) =
assert( is_vector(v) || is_matrix(v) || ( is_matrix(v[0],square=true) && is_consistent(v)),
"Invalid input.")
_product(v, 1, v[0]);
function _product(v, i=0, _tot) =
i>=len(v) ? _tot :
_product( v,
i+1,
( is_vector(v[i])? v_mul(_tot,v[i]) : _tot*v[i] ) );
// Function: cumprod()
// Synopsis: Returns the running cumulative product of a list of values.
// Topics: Math, Statistics
// See Also: sum(), mean(), median(), product(), cumsum()
// Usage:
// prod_list = cumprod(list, [right]);
// Description:
// Returns a list where each item is the cumulative product of all items up to and including the corresponding entry in the input list.
// If passed an array of vectors, returns a list of elementwise vector products. If passed a list of square matrices by default returns matrix
// products multiplying on the left, so a list `[A,B,C]` will produce the output `[A,BA,CBA]`. If you set `right=true` then it returns
// the product of multiplying on the right, so a list `[A,B,C]` will produce the output `[A,AB,ABC]` in that case.
// Arguments:
// list = The list to get the cumulative product of.
// right = if true multiply matrices on the right
// Example:
// cumprod([1,3,5]); // returns [1,3,15]
// cumprod([2,2,2]); // returns [2,4,8]
// cumprod([[1,2,3], [3,4,5], [5,6,7]])); // returns [[1, 2, 3], [3, 8, 15], [15, 48, 105]]
function cumprod(list,right=false) =
is_vector(list) ? _cumprod(list) :
assert(is_consistent(list), "Input must be a consistent list of scalars, vectors or square matrices")
assert(is_bool(right))
is_matrix(list[0]) ? assert(len(list[0])==len(list[0][0]), "Matrices must be square") _cumprod(list,right)
: _cumprod_vec(list);
function _cumprod(v,right,_i=0,_acc=[]) =
_i==len(v) ? _acc :
_cumprod(
v, right, _i+1,
concat(
_acc,
[
_i==0 ? v[_i]
: right? _acc[len(_acc)-1]*v[_i]
: v[_i]*_acc[len(_acc)-1]
]
)
);
function _cumprod_vec(v,_i=0,_acc=[]) =
_i==len(v) ? _acc :
_cumprod_vec(
v, _i+1,
concat(
_acc,
[_i==0 ? v[_i] : v_mul(_acc[len(_acc)-1],v[_i])]
)
);
// Function: convolve()
// Synopsis: Returns the convolution of `p` and `q`.
// Topics: Math, Statistics
// See Also: sum(), mean(), median(), product(), cumsum()
// Usage:
// x = convolve(p,q);
// Description:
// Given two vectors, or one vector and a path or
// two paths of the same dimension, finds the convolution of them.
// If both parameter are vectors, returns the vector convolution.
// If one parameter is a vector and the other a path,
// convolves using products by scalars and returns a path.
// If both parameters are paths, convolve using scalar products
// and returns a vector.
// The returned vector or path has length len(p)+len(q)-1.
// Arguments:
// p = The first vector or path.
// q = The second vector or path.
// Example:
// a = convolve([1,1],[1,2,1]); // Returns: [1,3,3,1]
// b = convolve([1,2,3],[1,2,1])); // Returns: [1,4,8,8,3]
// c = convolve([[1,1],[2,2],[3,1]],[1,2,1])); // Returns: [[1,1],[4,4],[8,6],[8,4],[3,1]]
// d = convolve([[1,1],[2,2],[3,1]],[[1,2],[2,1]])); // Returns: [3,9,11,7]
function convolve(p,q) =
p==[] || q==[] ? [] :
assert( (is_vector(p) || is_matrix(p))
&& ( is_vector(q) || (is_matrix(q) && ( !is_vector(p[0]) || (len(p[0])==len(q[0])) ) ) ) ,
"The inputs should be vectors or paths all of the same dimension.")
let( n = len(p),
m = len(q))
[for(i=[0:n+m-2], k1 = max(0,i-n+1), k2 = min(i,m-1) )
sum([for(j=[k1:k2]) p[i-j]*q[j] ])
];
// Function: sum_of_sines()
// Synopsis: Returns the sum of one or more sine waves at a given angle.
// Topics: Math, Statistics
// See Also: sum(), mean(), median(), product(), cumsum()
// Usage:
// sum_of_sines(a,sines)
// Description:
// Given a list of sine waves, returns the sum of the sines at the given angle.
// Each sine wave is given as an `[AMPLITUDE, FREQUENCY, PHASE_ANGLE]` triplet.
// - `AMPLITUDE` is the height of the sine wave above (and below) `0`.
// - `FREQUENCY` is the number of times the sine wave repeats in 360º.
// - `PHASE_ANGLE` is the offset in degrees of the sine wave.
// Arguments:
// a = Angle to get the value for.
// sines = List of [amplitude, frequency, phase_angle] items, where the frequency is the number of times the cycle repeats around the circle.
// Example:
// v = sum_of_sines(30, [[10,3,0], [5,5.5,60]]);
function sum_of_sines(a, sines) =
assert( is_finite(a) && is_matrix(sines,undef,3), "Invalid input.")
sum([ for (s = sines)
let(
ss=point3d(s),
v=ss[0]*sin(a*ss[1]+ss[2])
) v
]);
// Section: Random Number Generation
// Function: rand_int()
// Synopsis: Returns a random integer.
// Topics: Random
// See Also: rand_int(), random_points(), gaussian_rands(), random_polygon(), spherical_random_points(), exponential_rands()
// Usage:
// rand_int(minval, maxval, n, [seed]);
// Description:
// Return a list of random integers in the range of minval to maxval, inclusive.
// Arguments:
// minval = Minimum integer value to return.
// maxval = Maximum integer value to return.
// N = Number of random integers to return.
// seed = If given, sets the random number seed.
// Example:
// ints = rand_int(0,100,3);
// int = rand_int(-10,10,1)[0];
function rand_int(minval, maxval, n, seed=undef) =
assert( is_finite(minval+maxval+n) && (is_undef(seed) || is_finite(seed) ), "Input must be finite numbers.")
assert(maxval >= minval, "Max value cannot be smaller than minval")
let (rvect = is_def(seed) ? rands(minval,maxval+1,n,seed) : rands(minval,maxval+1,n))
[for(entry = rvect) floor(entry)];
// Function: random_points()
// Synopsis: Returns a list of random points.
// Topics: Random, Points
// See Also: rand_int(), random_points(), random_polygon(), spherical_random_points()
// Usage:
// points = random_points(n, dim, [scale], [seed]);
// Description:
// Generate `n` uniform random points of dimension `dim` with data ranging from -scale to +scale.
// The `scale` may be a number, in which case the random data lies in a cube,
// or a vector with dimension `dim`, in which case each dimension has its own scale.
// Arguments:
// n = number of points to generate. Default: 1
// dim = dimension of the points. Default: 2
// scale = the scale of the point coordinates. Default: 1
// seed = an optional seed for the random generation.
function random_points(n, dim, scale=1, seed) =
assert( is_int(n) && n>=0, "The number of points should be a non-negative integer.")
assert( is_int(dim) && dim>=1, "The point dimensions should be an integer greater than 1.")
assert( is_finite(scale) || is_vector(scale,dim), "The scale should be a number or a vector with length equal to d.")
let(
rnds = is_undef(seed)
? rands(-1,1,n*dim)
: rands(-1,1,n*dim, seed) )
is_num(scale)
? scale*[for(i=[0:1:n-1]) [for(j=[0:dim-1]) rnds[i*dim+j] ] ]
: [for(i=[0:1:n-1]) [for(j=[0:dim-1]) scale[j]*rnds[i*dim+j] ] ];
// Function: gaussian_rands()
// Synopsis: Returns a list of random numbers with a gaussian distribution.
// Topics: Random, Statistics
// See Also: rand_int(), random_points(), gaussian_rands(), random_polygon(), spherical_random_points(), exponential_rands()
// Usage:
// arr = gaussian_rands([n],[mean], [cov], [seed]);
// Description:
// Returns a random number or vector with a Gaussian/normal distribution.
// Arguments:
// n = the number of points to return. Default: 1
// mean = The average of the random value (a number or vector). Default: 0
// cov = covariance matrix of the random numbers, or variance in the 1D case. Default: 1
// seed = If given, sets the random number seed.
function gaussian_rands(n=1, mean=0, cov=1, seed=undef) =
assert(is_num(mean) || is_vector(mean))
let(
dim = is_num(mean) ? 1 : len(mean)
)
assert((dim==1 && is_num(cov)) || is_matrix(cov,dim,dim),"mean and covariance matrix not compatible")
assert(is_undef(seed) || is_finite(seed))
let(
nums = is_undef(seed)? rands(0,1,dim*n*2) : rands(0,1,dim*n*2,seed),
rdata = [for (i = count(dim*n,0,2)) sqrt(-2*ln(nums[i]))*cos(360*nums[i+1])]
)
dim==1 ? add_scalar(sqrt(cov)*rdata,mean) :
assert(is_matrix_symmetric(cov),"Supplied covariance matrix is not symmetric")
let(
L = cholesky(cov)
)
assert(is_def(L), "Supplied covariance matrix is not positive definite")
move(mean,list_to_matrix(rdata,dim)*transpose(L));
// Function: exponential_rands()
// Synopsis: Returns a list of random numbers with an exponential distribution.
// Topics: Random, Statistics
// See Also: rand_int(), random_points(), gaussian_rands(), random_polygon(), spherical_random_points()
// Usage:
// arr = exponential_rands([n], [lambda], [seed])
// Description:
// Returns random numbers with an exponential distribution with parameter lambda, and hence mean 1/lambda.
// Arguments:
// n = number of points to return. Default: 1
// lambda = distribution parameter. The mean will be 1/lambda. Default: 1
function exponential_rands(n=1, lambda=1, seed) =
assert( is_int(n) && n>=1, "The number of points should be an integer greater than zero.")
assert( is_num(lambda) && lambda>0, "The lambda parameter must be a positive number.")
let(
unif = is_def(seed) ? rands(0,1,n,seed=seed) : rands(0,1,n)
)
-(1/lambda) * [for(x=unif) x==1 ? 708.3964185322641 : ln(1-x)]; // Use ln(min_float) when x is 1
// Function: spherical_random_points()
// Synopsis: Returns a list of random points on the surface of a sphere.
// Topics: Random, Points
// See Also: rand_int(), random_points(), gaussian_rands(), random_polygon(), spherical_random_points()
// Usage:
// points = spherical_random_points([n], [radius], [seed]);
// Description:
// Generate `n` 3D uniformly distributed random points lying on a sphere centered at the origin with radius equal to `radius`.
// Arguments:
// n = number of points to generate. Default: 1
// radius = the sphere radius. Default: 1
// seed = an optional seed for the random generation.
// See https://mathworld.wolfram.com/SpherePointPicking.html
function spherical_random_points(n=1, radius=1, seed) =
assert( is_int(n) && n>=1, "The number of points should be an integer greater than zero.")
assert( is_num(radius) && radius>0, "The radius should be a non-negative number.")
let( theta = is_undef(seed)