Jump to content

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 0
}
// 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
ifswitch ax, ap := math.Abs(x) <, math.Abs(p); {
case ax < ap:
err = x - (sum - p)
}case elseap {< ax:
err = p - (sum - x)
}
Line 827 ⟶ 830:
sum += x
}
return sum / float64(len(v)), true
}
 
func main() {
for _, v := range [][]float64{
[]float64{}, // answer ismean 0returns perok task= descriptionfalse
[]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("Meanif ofm, %dok numbers:= is %g\n\n", lenmean(v),; mean(v))ok {
fmt.Printf("Mean of %d numbers is %g\n\n", len(v), m)
} else {
fmt.Println("Mean undefined\n")
}
}
}</lang>
{{out}}
Output:
<pre>Vector: []
Vector: []
Mean of 0 numbers is 0
Mean undefined
 
Vector: [+Inf +Inf]
Mean of 2 numbers is +Inf
 
Vector: [+Inf -Inf]
Mean of 02 numbers is 0NaN
 
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>
</pre>
 
=={{header|Groovy}}==
1,707

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.