See below

On 09/15/2013 06:48 PM, Unknown User wrote:
I have an array of numbers, and i want to find the percentage difference between all the elements.
Say my @a = ($a,$b,$c);
I need to calculate the percentage difference of element a with b, b with c and c with a. The 3 items above are an example, it can be hundreds of numbers. Is there an algorithm already existing for this, so that all elements are compared and none are missed?


Thanks

UU,

I am not sure whether or not an existing algorithm is out there or not... in fact, there may very well be a Math::PercentageDiffArray module on CPAN..

This bit of ugly code seems to work pretty well, though:

  use warnings;
  use strict;

  my @a = (15, 30, 45, 90, 120, 150);
  my @b;

  foreach my $idx (0..$#a) {
    $b[$idx] = (($a[($idx+1) % (scalar @a)] / $a[$idx]) - 1) * 100;
  }

  print map {"$_\n"} @b;

It was even uglier on the first iteration, so I re-did it this way so that it might be a bit clearer.

The index of the first operand "($idx+1) % (scalar @a)" simply says "use the element one greater than the current index, unless it is the last element.. and then use a zero".

Nathan

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to