Averages/Pythagorean means: Difference between revisions

imported>Regattaguru
 
(One intermediate revision by one other user not shown)
Line 3,243:
=={{header|RPL}}==
These words can be used either on vectors or lists.
{{works with|HP|28}}
≪ → array op
≪ array 1 GET 2 array SIZE
'''IF''' DUP2 > '''THEN''' DROP2 '''ELSE FOR''' j array GET op EVAL '''NEXT END'''
≫ ≫ '<span style="color:blue">REDUCE</span>' STO
≪ DUP ≪ + ≫ <span style="color:blue">REDUCE</span> SWAP SIZE /
≫ '<span style="color:blue">AMEAN</span>' STO
≪ DUP ≪ * ≫ <span style="color:blue">REDUCE</span> SWAP SIZE INV ^
≫ '<span style="color:blue">GMEAN</span>' STO
DUPSIZE LAST ≪ INV + ≫ <span style="color:blue">REDUCE</span> INV SWAP SIZE */
≫ '<span style="color:blue">HMEAN</span>' STO
 
{ 1 2 3 4 5 6 7 8 9 0 } <span style="color:blue">AMEAN</span>
{ 1 2 3 4 5 6 7 8 9 0 } <span style="color:blue">GMEAN</span>
[ 1 2 3 4 5 6 7 8 9 0 ] <span style="color:blue">HMEAN</span>
{{out}}
<pre>
Line 3,266 ⟶ 3,267:
1: 3.41417152147
</pre>
 
=={{header|Ruby}}==
{{works with|Ruby|1.9+}}
Line 3,533 ⟶ 3,535:
| Harmonic 10 3.414172 2.035664 10.57602
-----------------------------------------------------------------------------</syntaxhighlight>
=={{header|Swift}}==
<syntaxhighlight lang="text">
// Utility for easy creation of Double from any Numeric
extension Double {
init(withNum v: any Numeric) {
switch v {
case let ii as any BinaryInteger: self.init(ii)
case let ff as any BinaryFloatingPoint: self.init(ff)
default: self.init()
}
}
}
// Extension for numeric collections
extension Collection where Element: Numeric {
var arithmeticMean: Double {
self.reduce(0.0, {$0 + Double(withNum: $1)})/Double(self.count)
}
var geometricMean: Double {
pow(self.reduce(1.0, {$0 * Double(withNum: $1)}), 1.0/Double(self.count))
}
var harmonicMean: Double {
Double(self.count) / self.reduce(0.0, {$0 + 1.0/Double(withNum:$1)})
}
}
//Usage:
var c: [Int] = (1...10).map {$0}
 
print(c.arithmeticMean)
print(c.geometricMean)
print(c.harmonicMean)
 
// output:
// 5.5
// 4.528728688116765
// 3.414171521474055
</syntaxhighlight>
 
=={{header|Tcl}}==
Anonymous user