Averages/Median: Difference between revisions

Content added Content deleted
(→‎{{header|Bracmat}}: Reimplemented using recently introduced floating point functionality.)
Line 1,888: Line 1,888:
=={{header|Bracmat}}==
=={{header|Bracmat}}==


Each number is packaged in a little structure and these structures are accumulated in a sum. Bracmat keeps sums sorted, so the median is the term in the middle of the list, or the average of the two terms in the middle of the list. Notice that the input is converted to Bracmat's internal number representation, rational numbers, before being sorted. The output is converted back to 'double' variables. That last conversion is lossy.
Bracmat has no floating point numbers, so we have to parse floating point numbers as strings and convert them to rational numbers.
Each number is packaged in a little list and these lists are accumulated in a sum. Bracmat keeps sums sorted, so the median is the term in the middle of the list, or the average of the two terms in the middle of the list.


<syntaxhighlight lang="bracmat">(median=
<syntaxhighlight lang="bracmat">( ( median
begin decimals end int list med med1 med2 num number
= begin decimals end int list
, med med1 med2 num number
. 0:?list
. ( convertToRational
& whl
' ( @( !arg
=
: ?
. new$(UFP,'(.$arg:?V))
((%@:~" ":~",") ?:?number)
: ?ufp
((" "|",") ?arg|:?arg)
& (ufp..go)$
)
& (ufp..export)$(Q.V)
& @( !number
)
& 0:?list
: ( #?int "." [?begin #?decimals [?end
& whl
& !int+!decimals*10^(!begin+-1*!end):?num
| ?num
' ( !arg:%?number ?arg
)
& convertToRational$!number:?rationalnumber
)
& (!rationalnumber.)+!list:?list
& (!num.)+!list:?list
)
& !list:?+[?end
& ( !end*1/2:~/
& !list
: ?
+ [!(=1/2*!end+-1)
+ (?med1.?)
+ (?med2.?)
+ ?
& !med1*1/2+!med2*1/2:?med
| !list:?+[(div$(1/2*!end,1))+(?med.)+?
)
& (new$(UFP,'(.$med)).go)$
)
& out$(median$("4.1" 4 "1.2" "6.235" "7868.33"))
& out
$ ( median
$ ( "4.4"
"2.3"
"-1.7"
"7.5"
"6.6"
"0.0"
"1.9"
"8.2"
"9.3"
"4.5"
)
)
& !list:?+[?end
& ( !end*1/2:~/
& !list:?+[!(=1/2*!end+-1)+(?med1.)+(?med2.)+?
& !med1*1/2+!med2*1/2:?med
| !list:?+[(div$(1/2*!end,1))+(?med.)+?
)
)
& out$(median$(1 5 3 2 4))
& !med
& out$(median$(1 5 3 6 4 2))
);</syntaxhighlight>
);</syntaxhighlight>


Output:
<pre>4.0999999999999996E+00
<pre> median$" 4.1 4 1.2 6.235 7868.33"
4.4500000000000002E+00
41/10
3.0000000000000000E+00

3.5000000000000000E+00</pre>
median$"4.4, 2.3, -1.7, 7.5, 6.6, 0.0, 1.9, 8.2, 9.3, 4.5"
89/20

median$"1, 5, 3, 2, 4"
3

median$"1, 5, 3, 6, 4, 2"
7/2</pre>


=={{header|C}}==
=={{header|C}}==