Centroid of a set of N-dimensional points: Difference between revisions

Added Sidef
(Added BASIC256)
(Added Sidef)
 
(3 intermediate revisions by 2 users not shown)
Line 528:
 
=={{header|Perl}}==
===PDL library, with plot===
{{libheader|PDL}}
<syntaxhighlight lang="perl">use v5.36;
Line 569 ⟶ 570:
[0 0.25 0.25 0.25 0.25]</pre>
[[File:Centroid_plot_perl.png|center|thumb]]
===Direct calculation===
<syntaxhighlight lang="perl" line>
use v5.36;
 
sub centroid ($LoL) {
my $n = $#{ $LoL };
my $d = $#{ $LoL->@[0] };
my @C = 0 x ($d+1);
for my $i (0..$d) {
$C[$i] += $LoL->@[$_]->@[$i] for 0..$n;
$C[$i] /= $n+1
}
@C
}
 
say join ' ', centroid($_) for
[ [1,], [2,], [3,] ],
[ [8, 2], [0, 0] ],
[ [5, 5, 0], [10, 10, 0] ],
[ [1, 3.1, 6.5], [-2, -5, 3.4], [-7, -4, 9], [2, 0, 3] ],
[ [0, 0, 0, 0, 1], [0, 0, 0, 1, 0], [0, 0, 1, 0, 0], [0, 1, 0, 0, 0] ];
</syntaxhighlight>
{{out}}
<pre>
2
4 1
7.5 7.5 0
-1.5 -1.475 5.475
0 0.25 0.25 0.25 0.25
</pre>
 
=={{header|Phix}}==
Line 612 ⟶ 643:
(-1.5 -1.475 5.475)
(0 0.25 0.25 0.25 0.25)</pre>
 
=={{header|Sidef}}==
 
<syntaxhighlight lang="ruby">func centroid(l) {
l.combine {|*a| a.sum } »/» l.len
}
 
[
[ [1], [2], [3] ],
[ [8, 2], [0, 0] ],
[ [5, 5, 0], [10, 10, 0] ],
[ [1, 3.1, 6.5], [-2, -5, 3.4], [-7, -4, 9], [2, 0, 3] ],
[ [0, 0, 0, 0, 1], [0, 0, 0, 1, 0], [0, 0, 1, 0, 0], [0, 1, 0, 0, 0] ],
].each {
say centroid(_)
}</syntaxhighlight>
 
{{out}}
<pre>
[2]
[4, 1]
[15/2, 15/2, 0]
[-3/2, -59/40, 219/40]
[0, 1/4, 1/4, 1/4, 1/4]
</pre>
 
=={{header|Wren}}==
<syntaxhighlight lang="ecmascriptwren">var centroid = Fn.new { |pts|
var n = pts.count
if (n == 0) Fiber.abort("List must contain at least one point.")
Line 655 ⟶ 711:
{{libheader|Wren-math}}
Or, more concise using library methods - output identical.
<syntaxhighlight lang="ecmascriptwren">import "./seq" for Lst
import "./math" for Nums
 
2,747

edits