After writing this response I realized that you might be trying to calculate the least squares fit for multiple data sets at the same time. If you are, then the advice I gave isn't very useful. It turns out that closures might not be such a bad idea after all. Here is my attempt to solve the problem using closures.
#! /usr/bin/perl -w use strict; # Create an array of closures my @LS_closures = ( create_LS_closure(), create_LS_closure(), ); while( <> ) { my ( $x1, $y1, $x2, $y2 ) = split; # add the current data to the closure $LS_closures[0]{add}->( $x1, $y1 ); $LS_closures[1]{add}->( $x2, $y2 ); } # calculate the least squares coefficient my ( $a, $b ) = $LS_closures[0]{calcCoefs}->(); print "for the first set of data a = $a; b = $b\n"; ( $a, $b ) = $LS_closures[1]{calcCoefs}->(); print "for the second set of data a = $a; b = $b\n"; # ----------------------------------------------- # The closure generating subroutine sub create_LS_closure { # these variable are unique to each closure # created my $sum_x = 0; my $sum_y = 0; my $sum_x2 = 0; my $sum_xy = 0; my $n = 0; return { # This is the anonymous function for adding # data a to the least squares fit add => sub { my ($x, $y) = @_; $sum_x += $x; $sum_y += $y; $sum_x2 += $x * $x; $sum_xy += $x * $y; $n++; }, # This is the anonymous function for # computing the coefficients of the # least squares fit calcCoefs => sub { my $a = ( $sum_y * $sum_x2 - $sum_x * $sum_xy ) / ( $n * $sum_x2 - $sum_x * $sum_x ); my $b = ( $n * $sum_xy - $sum_x * $sum_y ) / ( $n * $sum_x2 - $sum_x * $sum_x ); return ($a, $b); } } }
When given the following input
-2 -3 -2 3 -1 -1 -1 1 0 1 0 -1 1 3 1 -3 2 5 2 -5 3 7 3 -7this program outputs
for the first set of data a = 1; b = 2 for the second set of data a = -1; b = -2which is exactly correct
The calling code appears to be quite flexible, and the closure could probably be moved to a module. So it appears that using closures to calculate least squares fits might not be such a bad idea!
Comments? Questions?
enjoy
In reply to Re: Closures and Statistics
by meta4
in thread Closures and Statistics
by dimmesdale
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |