Averages/Arithmetic mean: Difference between revisions
→{{header|Go}}: improved for task description, improved to handle Inf, updated output.
m (→{{header|REXX}}: added a comment in the header section. -- ~~~~) |
(→{{header|Go}}: improved for task description, improved to handle Inf, updated output.) |
||
Line 800:
)
func mean(v []float64) (m float64, ok bool) {
if len(v) == 0 {
return
}
// an algorithm that attempts to retain accuracy
// with widely different values.
var parts []float64
for _, x := range v {
Line 810 ⟶ 812:
sum := p + x
var err float64
case ax < ap:
err = x - (sum - p)
err = p - (sum - x)
}
Line 827 ⟶ 830:
sum += x
}
return sum / float64(len(v)), true
}
func main() {
for _, v := range [][]float64{
[]float64{}, //
[]float64{math.Inf(1), math.Inf(1)}, // answer is +Inf
// answer is NaN, and mean returns ok = true, indicating NaN
// is the correct result
[]float64{math.Inf(1), math.Inf(-1)},
[]float64{3, 1, 4, 1, 5, 9},
// large magnitude numbers cancel. answer is mean of small numbers.
[]float64{1e20, 3, 1, 4, 1, 5, 9, -1e20},
[]float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11},
[]float64{10, 20, 30, 40, 50, -100, 4.7, -11e2},
} {
fmt.Println("Vector:", v)
fmt.Printf("Mean of %d numbers is %g\n\n", len(v), m)
} else {
fmt.Println("Mean undefined\n")
}
}
}</lang>
{{out}}
<pre>
Vector: []
Mean of 0 numbers is 0▼
Mean undefined
Vector: [+Inf +Inf]
Mean of 2 numbers is +Inf
Vector: [+Inf -Inf]
Vector: [3 1 4 1 5 9]
Line 856 ⟶ 879:
Vector: [10 20 30 40 50 -100 4.7 -1100]
Mean of 8 numbers is -130.6625
</pre>
=={{header|Groovy}}==
|