diff options
author | B. Watson <urchlay@slackware.uk> | 2025-01-09 15:40:54 -0500 |
---|---|---|
committer | B. Watson <urchlay@slackware.uk> | 2025-01-09 15:40:54 -0500 |
commit | 14a3ab25c9d4d404e544f3b44a4ad5e3bedf5ae6 (patch) | |
tree | 9009230800ea06cca8b5872a6979a334efcf26fc | |
parent | 98945a09973e1cba76e7b2da4d5fd238d193f393 (diff) | |
download | stupid-irssi-tricks-14a3ab25c9d4d404e544f3b44a4ad5e3bedf5ae6.tar.gz |
calc.pl: make rand() accept args
-rw-r--r-- | calc.pl | 31 |
1 files changed, 30 insertions, 1 deletions
@@ -20,6 +20,7 @@ our %accumulators; sub init_parser { $parser = new Math::Calc::Parser; + $parser->remove_functions('rand'); $parser->add_functions( deg => { args => 1, code => sub { $_[0] * 180 / pi; } }, rad => { args => 1, code => sub { $_[0] / 180 * pi; } }, @@ -35,9 +36,31 @@ sub init_parser { avg => { args => '+', code => \&average }, ohms => { args => '+', code => \¶llel_resistors }, + rand => { args => '+', code => \&random }, + randi => { args => '+', code => \&random_int }, ); } +# 0 args, or 1 arg if it's 0: random 0 <= x < 1. +# 1 arg (not 0): random 0 <= x < arg. +# 2 args: random arg1 <= x < arg2. +sub random { + if(!@_ || (@_ == 1 && $_[0] == 0)) { + return rand(1); + } elsif(@_ == 1) { + return rand($_[0]); + } elsif(@_ == 2) { + die "can't generate random number between $_[0] and $_[1]" if $_[0] == $_[1]; + @_ = ($_[0], $_[1]) if $_[0] > $_[1]; + return rand($_[1] - $_[0]) + $_[0]; + } + die "requires 0, 1, or 2 arguments."; +} + +sub random_int { + return int(random(@_)); +} + # mean (most people call it an average so I went with that) sub average { die "requires at least 2 arguments\n" if @_ < 2; @@ -386,7 +409,13 @@ Calculates parallel resistance. Takes at least 2 arguments. =item rand -Random value between 0 and 1 (exclusive of 1). No arguments. +With 0 arguments: same as B<rand(1)>. With 1 argument: random number +between 0 and the argument (or 1, if the arg is 0). With 2 arguments: +random number between the 2 arguments. + +=item randi + +Same as B<rand>, but truncates the result to an integer. 0, 1, or 2 arguments. =item round |