SPUG:Max of two floats?

Sanford Morton smorton at pobox.com
Tue Jan 28 14:04:44 CST 2003


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.

Thanks,
Sandy Morton





More information about the spug-list mailing list