SPUG:Max of two floats?

Asim Jalis asimjalis at acm.org
Tue Jan 28 14:15:18 CST 2003


On Tue, Jan 28, 2003 at 12:04:44PM -0800, Sanford Morton wrote:
> A precision bug was discovered in one of my modules,
> Statistics::OLS, http://www.speakeasy.org/~cgires/modules/ The
> result of a calculation, which theoretically can never be
> negative, sometimes is a tiny negative number on weird data
> sets. (Definition of weird; blows my modules up.)
> 
> I want to ensure that these sorts of things are non-negative:
> 
>   # sum of squared deviations of X and Y
>   $self->{'_ssdX'} = $sumXX - $sumX**2/$n; 
>   $self->{'_ssdY'} = $sumYY - $sumY**2/$n;
>   $self->{'_ssdXY'} = $sumXY - $sumX*$sumY/$n;
> 
> I couldn't find a max(,) function in Perl, so should I use the
> ? operator? I was thinking something like this might be
> fastest:
> 
>   { my $tmp;
> 
>     $self->{'_ssdX'}  =  ($tmp = $sumXX - $sumX**2/$n > 0) ? $tmp : 0;
>     $self->{'_ssdY'}  =  ($tmp = $sumYY - $sumY**2/$n > 0) ? $tmp : 0;
>     $self->{'_ssdXY'} =  ($tmp = $sumXY - $sumX*$sumY/$n > 0) ? $tmp : 0;
>   }
> 
> Programming Perl and The Perl Cookbook appear not to have a
> canonical solution.


You could also use a regular expression:

    # sum of squared deviations of X and Y
    $self->{'_ssdX'} = $sumXX - $sumX**2/$n; 
    $self->{'_ssdY'} = $sumYY - $sumY**2/$n;
    $self->{'_ssdXY'} = $sumXY - $sumX*$sumY/$n;
    
    $self->{'_ssdX'}  =~ s/^-.*$/0.0/;
    $self->{'_ssdY'}  =~ s/^-.*$/0.0/;
    $self->{'_ssdXY'} =~ s/^-.*$/0.0/;

Probably not as readable as your solution. And it's not clear
that it is any better. I am just letting my TMTOWTDI get a little
wild here.


Asim



More information about the spug-list mailing list