Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Determine steps between two numbers

by thmsdrew (Scribe)
on Sep 05, 2012 at 12:22 UTC ( #991822=CUFP: print w/replies, xml ) Need Help??

The following program will find the steps between two numbers. Give it two numbers to find steps between, and the number of steps you want it to find, and it'll list them for you.


$ 1 10 5 1, 3.25, 5.5, 7.75, 10 $ 10.5 -10.7 4 10.5, 3.43333333333333, -3.63333333333333, -10.7

#!/usr/bin/perl use strict; use warnings; my ($first, $second, $steps) = @ARGV; $steps = int $steps; my $increment = ($second - $first) / ($steps - 1); my @array = ($first); for (2..$steps) { push @array, $first += $increment; } print join(", ", @array) . "\n";

Updated to make a bit more sense. I don't always need to list it in a specific order. It makes more sense for the order to be determined by the input.

Replies are listed 'Best First'.
Re: Determine steps between two numbers
by hbm (Hermit) on Sep 05, 2012 at 13:12 UTC

    Since you always assemble your steps in increasing order, you could do this:

    #!/usr/bin/perl use strict; use warnings; my ($first, $second, $steps) = @ARGV; $steps = int $steps; if ($first > $second) { ($first,$second) = ($second,$first); } my $increment = ($first - $second) / ($steps - 1); my @array = ($first); for (2..$steps) { push @array, $first -= $increment; } print join(", ", @array) . "\n";
      IMHO in such case the variable name should be changed from 'increment' to 'decrement'. Or better - change algorithm to more intuitive:
      my $increment = ($second - $first) / ($steps - 1); ... push @array, $first += $increment;
      And one-line @array generator as alternative:

      my @array = map { $first + $increment * $_ } 0 .. $steps - 1;

        Thanks. I transferred this over from my Java implementation of it and didn't quite get it right, so I did some stuff to make it work. You helped me get it back to what it was originally. Not too confident in the one-line generator you have there, but it'd be a nice touch anyway.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: CUFP [id://991822]
Approved by Corion
Front-paged by Arunbear
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (6)
As of 2018-08-15 13:04 GMT
Find Nodes?
    Voting Booth?
    Asked to put a square peg in a round hole, I would:

    Results (160 votes). Check out past polls.