in reply to Re: substitution "0" in decimals
in thread substitution "0" in decimals

This is interesting, but a lot of people try to treat problems as regex problems rather than just doing what they are thinking.

What you're probably thinking is, "If it has a dot, then remove ending 0's." What you're saying is "replace a dot followed by as few digits as possible, followed by as many zeros as are present, with the part before the zeros." Notice how they aren't the same. That's a code smell for me. And, interestingly, it's slower than doing what you said. Let's try it out. I've provided a micro-optimisation of replacing the * with a + - which means that if there are no zeros, the regex fails, and no substitution is performed, but I have your original (single-splat) still there for comparison. Note that this is likely a premature optimisation, but at the same time, it's so trivial that it's worth making the change. Changing it to the conditional or conditional2 examples would be more drastic based on optimisation alone unless you take my advice to line up your algorithm in your head with the one in your code.

#!/usr/bin/perl use common::sense; use Benchmark qw(cmpthese); my @N = qw(1230.1200 10332.0120 1200 153.56); cmpthese(-1, { 'single-splat' => sub { my @n = @N; for (@n) { s/(\.\d*?)0*$/$1/; } }, 'single' => sub { my @n = @N; for (@n) { s/(\.\d*?)0+$/$1/; } }, 'conditional' => sub { my @n = @N; for (@n) { s/0+$// if /\./; } }, 'conditional2' => sub { my @n = @N; for (@n) { s/0+$// if /\.\d+$/; } }, });
And the results on my machine are:
Rate single-splat single conditional2 conditio +nal single-splat 156392/s -- -25% -43% - +53% single 208524/s 33% -- -24% - +38% conditional2 275692/s 76% 32% -- - +17% conditional 334042/s 114% 60% 21% + --
That is, your original is the slowest (because I provided a test where yours does a substitution that does nothing while 'single' avoids triggering any modification of the string during the same run), followed by my micro-optimisation (micro? 33% better for these test cases?). The 'conditional' code shows closer to what you're probably thinking, though 'conditional2', which is significantly slower (as it needs to test more of each string), is probably just that tiny bit more accurate (and accuracy beats speed).

Replies are listed 'Best First'.
Re^3: substitution "0" in decimals
by kennethk (Abbot) on Dec 09, 2009 at 16:15 UTC
    I was certainly aware of the dissonance between the goal of simply stripping zeros and the replacement scheme I used. I was, however, hung up on "Variable length lookbehind not implemented in regex" (i.e. s/0+$(?<=\.\d+)//; or some such other non-functional code).