Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- use strict;
- use warnings;
- use feature 'say';
- my $data = [];
- while (<>) {
- chomp;
- my ($x, $dummy1, $y, $dummy2) = split;
- push @$data, [$x, $y];
- }
- my $a;
- my $b;
- while (1) {
- my $sum_xy = 0.;
- my $sum_x = 0.;
- my $sum_y = 0.;
- my $sum_x2 = 0.;
- foreach my $d (@$data) {
- my ($x, $y) = @$d;
- $sum_xy += $x * $y;
- $sum_x += $x;
- $sum_y += $y;
- $sum_x2 += $x ** 2;
- }
- my $n = @$data;
- $a = ($n * $sum_xy - $sum_x * $sum_y) / ($n * $sum_x2 - $sum_x ** 2);
- $b = ($sum_x2 * $sum_y - $sum_xy * $sum_x) / ($n * $sum_x2 - $sum_x ** 2);
- my $ys = 0.;
- foreach my $d (@$data) {
- my ($x, $y) = @$d;
- $ys += ($y - $a * $x - $b) ** 2;
- }
- my $error = 3 * sqrt($ys / ($n - 1));
- my $i = 0;
- foreach my $d (@$data) {
- my ($x, $y) = @$d;
- splice @$data, $i, 1 if abs($y - $a * $x - $b) >= $error;
- $i++;
- }
- last if $n == @$data;
- }
- say "y = ${a} * x + ${b}";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement