in reply to Re: Subroutine not correct (I think)
in thread Subroutine not correct (I think)

The coming up to zero part makes a lot of sense. Do you have any idea how I would start fixing that?

Replies are listed 'Best First'.
Re^3: Subroutine not correct (I think)
by pme (Monsignor) on Jun 17, 2015 at 13:31 UTC
    This piece of code may do something similar what you need.
    use strict; use warnings; use diagnostics; sub distance { my ($aa, $bb) = @_; return sqrt(($aa->[0] - $bb->[0])**2 + ($aa->[1] - $bb->[1])**2 + ($aa->[2] - $bb->[2])**2); } my $source = "./CONTCAR"; open(IN, '<', $source) or die "Couldn't open $source: $!\n"; my @data = map [ split ], grep /\S/, <IN>; foreach my $d1 (@data) { foreach my $d2 (@data) { printf "($d1->[0],$d1->[1],$d1->[2]) <-> ($d2->[0],$d2->[1],$d +2->[2]) = %f\n", distance($d1, $d2); } } close IN; print "Done.\n";
      That's so beautiful. Thank you. It is greatly appreciated. I understand the foreach loop a lot better with an example, thanks.
Re^3: Subroutine not correct (I think)
by roboticus (Chancellor) on Jun 17, 2015 at 13:43 UTC

    jcklasseter:

    Yeah, just get rid of the -$* part. Normally, you'd compute the distance like:

    return sqrt( ($x2 - $x1)**2 + ($y2 - $y1)**2 + ($z2 - $z1)**2 );

    But another way to think of it would be:

    my $dx = $x2 - $x1; my $dy = $y2 - $y1; my $dz = $z2 - $z1; return sqrt( $dx**2 + $dy**2 + $dz**2 );

    Your map statement is computing dx, dy and dz (you've just labelled them as x, y and z), so after your map statement, you can just use:

    return sqrt( $x**2 + $y**2 + $z**2 );

    Though I'd suggest renaming the variables x, y and z to clarify the code.

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

Re^3: Subroutine not correct (I think)
by locked_user sundialsvc4 (Abbot) on Jun 17, 2015 at 13:18 UTC
      I get the 'Subract X from itself and get 0' part. But what I don't get is how to fix the code to have it do what I want; I.E x2-x1 iteratively.