Averages/Median: Difference between revisions

→‎{{header|Rust}}: Took out compare function which was masking that there is no way to define an absolute ordering on floats, made it panic instead of silently fail
m (Added Sidef language)
(→‎{{header|Rust}}: Took out compare function which was masking that there is no way to define an absolute ordering on floats, made it panic instead of silently fail)
Line 2,186:
Sorting, then obtaining the median element:
 
<lang rust>usefn stdmedian(mut xs::cmp::Ordering; Vec<f64>) -> f64 {
// sort in ascending order, panic on f64::NaN
use std::cmp::Ordering::{Less, Equal, Greater};
xs.sort_by(|x,y| x.partial_cmp(y).unwrap() );
 
let n = xs.len();
fn compare(&x: &f64, &y: &f64) -> Ordering {
if xn <% y2 {== Less0 }{
else if x == y(xs[n/2] {+ Equalxs[n/2 }+ 1]) / 2.0
} else { Greater }
xs[n/2]
}
}
 
fn main() {
fn median(mut xs: Vec<f64>) -> f64 {
let nums = vec![2.,3.,5.,0.,9.,82.,353.,32.,12.];
xs.sort_by(compare);
println!("{:?}", median(nums))
let n = xs.len();
let i = n / 2;
if n % 2 == 0 {
(xs[i] + xs[i + 1]) / 2.0
} else {
xs[i]
}
}</lang>
 
{{out}}
<pre>9</pre>
 
=={{header|Scala}}==
Anonymous user