如何在坐标列表中找到最大的斜率值?

问题描述 投票:0回答:1

我想弄清楚当我有下面这种格式的数据时如何确定最大/最大斜率值。我将这些数据存储在一个数组中。前两列分别是X和Y坐标。我基本上想要将这些数据中的每一个可能的对插入斜率公式并确定最高可能值。

数据格式:

6.3 -7.2
-5.6 -2.4
2.1 7.8
5.2 1.4

到目前为止,我有:

sub maxSlope {
my @data; #Contains all the values
foreach $line (@data){
  @split_data = split(' ', $line);
  my ($x1, $y1) = ($split_data[0], $[split_data[1]);
  }

  #$my_slope = ($y2-$y1)/($x2-$x1); 
}

到目前为止,我只能在两个变量中得到第一对。我很难弄清楚如何在两个变量($x2, $y2)中得到下一对,并通过斜率公式(y2-y1/x2-x1)计算给定数据集的每个可能的对。任何帮助都非常感谢!

arrays perl
1个回答
0
投票

要使用所有点对,对于每个点,您需要遍历所有其他点(但不重复)。

我已经将工作分为首先构建所有斜率点的列表,然后找到最上面的斜率点,以获得灵活性,以便您可以更轻松地进一步实验和调整。见下面的评论。

use warnings;
use strict;
use feature 'say';    
use Data::Dump qw(dd);

use List::Util qw(reduce);

my @data = ('6.3 -7.2', '-5.6 -2.4', '2.1 7.8', '5.2 1.4');

my $rslopes = get_slopes(\@data);    
#dd $rslopes;

my $top = reduce { ($a->[0] > $b->[0]) ? $a : $b } @$rslopes;

say "$top->[0]  for (@{$top->[1]}) and (@{$top->[2]})";

sub get_slopes {
    my @data = @{$_[0]};
    my @slopes;

    while (my $line = shift @data) {
        my ($x1, $y1) = split ' ', $line;
        for (@data) {
            my ($x2, $y2) = split;
            push @slopes, [ ($y2-$y1)/($x2-$x1), [$x1, $y1], [$x2, $y2] ];  
        }
    }   
    return \@slopes;
}

这打印出最大的斜率及其点,使用List::Util::reduce找到。评论:

  • 结果存储在具有元素[slope, [pt1], [pt2]]的数组中,因为斜率在精度范围内可以相等,因此不能使用散列slope => [[pt1], [pt2]]
  • 一个值是从数组中进行的shifted,这样就可以将所有剩余的值与它进行比较。一旦删除了最后一个,就会有一个额外的(不需要的)split和赋值
  • 另一种方法是使用嵌套的for循环,其中内部循环从外部的i+1迭代。小心安排索引,使其不会越过帖子
  • 如果你真的只需要那个最大的斜率将reduce线移动到sub中,将sub重命名为max_slope(或类似),并返回顶部斜率的数组slope, [pt1], [pt2](或其ref)。或者在计算它们时比较值,并且您不需要reduce

要全部查看(排序),而不是仅查找最大的一个

my @sorted_slopes = sort { $b->[0] <=> $a->[0] } @$rslopes; 

for (@sorted_slopes) {
    printf "%6.3f for (%4.1f %4.1f) and (%4.1f %4.1f)\n",  
        $_->[0], @{$_->[1]}, @{$_->[2]};
} 

与输出

 1.325 for (-5.6 -2.4) and ( 2.1  7.8)
 0.352 for (-5.6 -2.4) and ( 5.2  1.4)
-0.403 for ( 6.3 -7.2) and (-5.6 -2.4)
-2.065 for ( 2.1  7.8) and ( 5.2  1.4)
-3.571 for ( 6.3 -7.2) and ( 2.1  7.8)
-7.818 for ( 6.3 -7.2) and ( 5.2  1.4)
© www.soinside.com 2019 - 2024. All rights reserved.