Perl does have maths functions built in: just its idea of the functions you might need are on par with a 1970s minicomputer. There are all the ones I could find:
#!/usr/bin/env perl
# maths_builtins.pl - some (all?) of the libm functions built in to Perl
# scruss - 2021-05
my $val = -1.234;
print 'abs(', $val, ')', "\t= ", abs($val), "\n";
my $pi = 4 * atan2( 1, 1 );
print '4*atan2(1,1)', "\t= ", $pi, "\t(= π)", "\n";
print 'cos(π/6)', "\t= ", cos( $pi / 6 ), "\n";
my $e = exp(1);
print 'exp(1)', "\t\t= ", $e, "\t(= e)", "\n";
print 'int(', $val, ')', "\t= ", int($val), "\n";
print 'log(e)', "\t\t= ", log($e), "\n";
print 'sin(π/6)', "\t= ", sin( $pi / 6 ), "\n";
print 'sqrt(3)/2', "\t= ", sqrt(3) / 2, "\n";
print 'sqrt(3)**2', "\t= ", sqrt(3)**2, "\n";
exit;
resulting in:
abs(-1.234) = 1.234
4*atan2(1,1) = 3.14159265358979 (= π)
cos(π/6) = 0.866025403784439
exp(1) = 2.71828182845905 (= e)
int(-1.234) = -1
log(e) = 1
sin(π/6) = 0.5
sqrt(3)/2 = 0.866025403784439
sqrt(3)**2 = 3
Note that instead of a pow()
function, Perl has the **
operator, just like FORTRAN does. You don't get a tan()
function, because that's sin($x)/cos($x)
. If you need other transcendental functions, that's why they put the trigonometric functions table (PDF, p.39) in all good programming books.
I can't recall ever using or needing ceil()
or floor()
myself, but Perl missing sgn()
as a builtin gets me every time. Since Perl is a typeless scripting language at heart, numeric gardening tasks like rounding can already be done with string functions such as sprintf "%.f", $val
.