Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Re: Subroutine not correct (I think)

by pme (Prior)
on Jun 17, 2015 at 13:08 UTC ( #1130794=note: print w/replies, xml ) Need Help??

in reply to Subroutine not correct (I think)

Hi jcklasseter,

I am not really understand what would you like to do with your input data. But I can point out two things.

printf has three format specifier and five values.

printf OUT "%s to %s Distance=%.5f\n", $data[$i][0], $data[$j][0], $data[$i][2], $data[$j][2], distance(\@coords_i, \@coords_j);

($x - $x), ($y - $y) and ($z - $z) are always equal to zero.

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

Replies are listed 'Best First'.
Re^2: Subroutine not correct (I think)
by jcklasseter (Sexton) on Jun 17, 2015 at 13:11 UTC
    The coming up to zero part makes a lot of sense. Do you have any idea how I would start fixing that?
      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.


      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.


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

        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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1130794]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (4)
As of 2020-01-18 12:58 GMT
Find Nodes?
    Voting Booth?