Averages/Mean time of day: Difference between revisions

Content added Content deleted
No edit summary
m (→‎{{header|Perl}}: added v5.36 version)
Line 1,743: Line 1,743:


=={{header|Perl}}==
=={{header|Perl}}==
===Traditional===
Using the core module <code>Math::Complex</code> to enable use of complex numbers. The <code>POSIX</code> CPAN module provides the <code>fmod</code> routine for non-integer modulus calculations.
Using the core module <code>Math::Complex</code> to enable use of complex numbers. The <code>POSIX</code> CPAN module provides the <code>fmod</code> routine for non-integer modulus calculations.
{{trans|Raku}}
{{trans|Raku}}
<lang Perl>use POSIX 'fmod';
<lang Perl>use strict;
use warnings;
use POSIX 'fmod';
use Math::Complex;
use Math::Complex;
use List::Util qw(sum);
use List::Util qw(sum);
Line 1,777: Line 1,780:
@times = ("23:00:17", "23:40:20", "00:12:45", "00:17:19");
@times = ("23:00:17", "23:40:20", "00:12:45", "00:17:19");
print mean_time(@times) . " is the mean time of " . join(' ', @times) . "\n";</lang>
print mean_time(@times) . " is the mean time of " . join(' ', @times) . "\n";</lang>
{{out}}
<pre>23:47:43 is the mean time of 23:00:17 23:40:20 00:12:45 00:17:19</pre>
===v5.36===
As previous, but using features from an up-to-date release of Perl, e.g. strict/warn/subroutine signatures without the <code>use</code> boilerplate.
<lang perl>use v5.36;
use POSIX 'fmod';
use Math::Complex;
use List::Util 'sum';
use utf8;

use constant τ => 2 * 2 * atan2(1, 0);

sub R_to_ToD ($radians) { my $x = $radians * 86400 / τ; sprintf '%02d:%02d:%02d', fm($x/3600,24), fm($x/60,60), fm($x,60) }
sub ToD_to_R ($h,$m,$s) { (3600*$h + 60*$m + $s) * τ / 86400 }
sub fm ($n,$b) { my $x = fmod($n,$b); $x += $b if $x < 0 }
sub cis ($radians) { cos($radians) + i*sin($radians) }
sub phase ($Θ) { arg( $Θ ) }
sub mean_time(@t) { R_to_ToD phase sum map { cis ToD_to_R split ':', $_ } @t }

my @times = <23:00:17 23:40:20 00:12:45 00:17:19>;
say my $result = mean_time(@times) . ' is the mean time of ' . join ' ', @times;</lang>
{{out}}
{{out}}
<pre>23:47:43 is the mean time of 23:00:17 23:40:20 00:12:45 00:17:19</pre>
<pre>23:47:43 is the mean time of 23:00:17 23:40:20 00:12:45 00:17:19</pre>