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. |
|||
⚫ | |||
<syntaxhighlight lang="bracmat">(median |
<syntaxhighlight lang="bracmat">( ( median |
||
= begin decimals end int list |
|||
, med med1 med2 num number |
|||
⚫ | |||
. ( convertToRational |
|||
⚫ | |||
= |
|||
. new$(UFP,'(.$arg:?V)) |
|||
: ?ufp |
|||
( |
& (ufp..go)$ |
||
) |
& (ufp..export)$(Q.V) |
||
) |
|||
⚫ | |||
: ( #?int "." [?begin #?decimals [?end |
|||
⚫ | |||
& !int+!decimals*10^(!begin+-1*!end):?num |
|||
' ( !arg:%?number ?arg |
|||
& convertToRational$!number:?rationalnumber |
|||
) |
& (!rationalnumber.)+!list:?list |
||
) |
|||
⚫ | |||
⚫ | |||
& !list |
|||
: ? |
|||
⚫ | |||
+ (?med1.?) |
|||
+ (?med2.?) |
|||
+ ? |
|||
⚫ | |||
⚫ | |||
) |
|||
& (new$(UFP,'(.$med)).go)$ |
|||
) |
|||
⚫ | |||
& out |
|||
$ ( median |
|||
$ ( "4.4" |
|||
"2.3" |
|||
"-1.7" |
|||
"7.5" |
|||
"6.6" |
|||
"0.0" |
|||
"1.9" |
|||
"8.2" |
|||
"9.3" |
|||
"4.5" |
|||
) |
) |
||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
) |
) |
||
⚫ | |||
& !med |
|||
⚫ | |||
);</syntaxhighlight> |
);</syntaxhighlight> |
||
Output: |
|||
<pre>4.0999999999999996E+00 |
|||
⚫ | |||
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 |
|||
⚫ | |||
3 |
|||
⚫ | |||
7/2</pre> |
|||
=={{header|C}}== |
=={{header|C}}== |