Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Clean log_10 ?

by davido (Cardinal)
on Nov 28, 2019 at 18:22 UTC ( #11109381=note: print w/replies, xml ) Need Help??


in reply to Clean log_10 ?

Math::BigInt:

sub blog10 { my $bn = shift; require Math::BigInt; return (ref($bn) ? $bn->copy : Math::BigInt->new($bn))->blog(10); } my $bn = 1e12; my $blog10 = blog10($bn); print "blog10($bn): $blog10\n"; print "mod($blog10,3): ", $blog10 % 3, "\n"; print "int($blog10): ", int($blog10), "\n";

The output:

blog10(1000000000000): 12 mod(12,3): 0 int(12): 12

...which should be what you expect it to be.

This does silently upgrade your number to a Math::BigInt object. Calling ref($blog10) would return Math::BigInt, for example. If that's objectionable, modify your blog10 function as follows:

return (ref($bn) ? $bn->copy : Math::BigInt->new($bn))->blog(10)->numi +fy;

You could make this even more "black box" by auto-decorating and auto-undecorating based on logic:

sub blog10 { my $n = shift; my $bn = ref($n) ? $n->copy : do { require Math::BigInt; Math::BigInt->new($n) }; my $ret = $bn->blog(10); return ref($n) ? $ret : $ret->numify; }

Dave

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11109381]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2020-06-07 04:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you really want to know if there is extraterrestrial life?



    Results (42 votes). Check out past polls.

    Notices?