Advertisement
cd62131

LeastSquaresMethod

Jul 27th, 2014
442
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 0.93 KB | None | 0 0
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. use feature 'say';
  5. my $data = [];
  6. while (<>) {
  7.   chomp;
  8.   my ($x, $dummy1, $y, $dummy2) = split;
  9.   push @$data, [$x, $y];
  10. }
  11. my $a;
  12. my $b;
  13. while (1) {
  14.   my $sum_xy = 0.;
  15.   my $sum_x = 0.;
  16.   my $sum_y = 0.;
  17.   my $sum_x2 = 0.;
  18.   foreach my $d (@$data) {
  19.     my ($x, $y) = @$d;
  20.     $sum_xy += $x * $y;
  21.     $sum_x += $x;
  22.     $sum_y += $y;
  23.     $sum_x2 += $x ** 2;
  24.   }
  25.   my $n = @$data;
  26.   $a = ($n * $sum_xy - $sum_x * $sum_y) / ($n * $sum_x2 - $sum_x ** 2);
  27.   $b = ($sum_x2 * $sum_y - $sum_xy * $sum_x) / ($n * $sum_x2 - $sum_x ** 2);
  28.   my $ys = 0.;
  29.   foreach my $d (@$data) {
  30.     my ($x, $y) = @$d;
  31.     $ys += ($y - $a * $x - $b) ** 2;
  32.   }
  33.   my $error = 3 * sqrt($ys / ($n - 1));
  34.   my $i = 0;
  35.   foreach my $d (@$data) {
  36.     my ($x, $y) = @$d;
  37.     splice @$data, $i, 1 if abs($y - $a * $x - $b) >= $error;
  38.     $i++;
  39.   }
  40.   last if $n == @$data;
  41. }
  42. say "y = ${a} * x + ${b}";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement