[PLUG] OT: Formula For Determining # Of Digits In An Integer
Eric Wilhelm
ewilhelm at sbcglobal.net
Thu Feb 17 23:11:01 UTC 2005
# The following was supposedly scribed by
# Jason Van Cleve
# on Thursday 17 February 2005 04:31 pm:
>> y = 1;
>> while (x /= 10)
>> y++;
>
>This is basically what I have now. It's just that the method I'm
>writing is already called in a loop, so I wanted a single-operation
>formula instead of a loop algorithm.
Long version of Galens reply:
You might want to benchmark the loop vs the log() method. I'm not sure
exactly how java does it or whether it's somehow native in the
processor, but IIRC from mathematics, logarithms are only computable as
an infinite series. So, barring some magic happening in the processor
that I don't know about, a hand-written log() function (which iterates
until the desired accuracy is reached (and remember, you're going to
call this twice)) is going to be slower than your simple reductive
loop.
Ok, so none of the details are too sharp here. Point is: benchmark.
Don't assume that mathematical elegance is always faster than brute
force.
Anyway, I'd probably just do length(sprintf("%0.0f", $num)) in perl
(assuming a positive number.)
--Eric
--
Cult: A small, unpopular religion.
Religion: A large, popular cult.
-- Unknown
---------------------------------------------
http://scratchcomputing.com
---------------------------------------------
More information about the PLUG
mailing list