0

I have a file with 17294 particles and for each particle I have x,y,z in three 3 columns (x,y,z). Z=0 for every particle so the problem is 2-D. I want to convert the Cartesian coordinates to polar and save them in the same file (4th column for r and 5th column fro θ). To begin with I tried to convert x,y only to r and save it in different file, here is my code:

while read x y z; do
   r=$(( $x*$x+$y*$y )) | bc
   r=$( echo "scale=3;sqrt($r)" | bc -l )
   echo $r >> rTh.dat
done < TP_xyz.dat

I get an error like this :

./xyToRTh.sh: line 6: 
2.0059765754498855*2.0059765754498855+1.8715584950948734*1.8715584950948734 : syntax error: invalid arithmetic operator
(error token is ".0059765754498855*2.0059765754498855+1.8715584950948734*1.8715584950948734 ")
(standard_in) 1: syntax error

Here is the form of the particles data (7 first particles):

 2.2573374744307952        1.2118823295321732        0.0000000000000000     
 1.5877269404049552        2.0106312183498303        0.0000000000000000     
 -2.3002441197354102       0.99907356258704294        0.0000000000000000     
 0.92072919084479099        2.3995221040664498        0.0000000000000000     
 0.67981176735521276        2.4186181486021687        0.0000000000000000     
 2.1297085617142675       -1.3495832035165336        0.0000000000000000     
 -6.1805611083798166E-002  -2.4993700771441976        0.0000000000000000

Any help would be useful. Thank you in advance.

jww
  • 97,681
  • 90
  • 411
  • 885
  • Is Bash the right tool for the job here? You should probably show the first few lines of your data file. It will help with your Bash question. And someone may provide a better solution, like with Awk or Python. – jww Dec 05 '19 at 13:03
  • `r=$(( $x*$x+$y*$y )) | bc` - either forward the operation to `bc` or use `$(( .. ))` arithmetic expansion. – KamilCuk Dec 05 '19 at 13:13
  • 1
    `r=$(( $x*$x+$y*$y )) | bc` isn't valid syntax. You can't use bash to handle floating arithmetics so `$(( ... ))` won't work, it looks like you want to use `r=$( echo "$x*$x+$y*$y" | bc)` instead – Aaron Dec 05 '19 at 13:13
  • bc won't understand the exponent notation E -002, you will have to use awk by the way ... and it will be faster. – Andre Gelinas Dec 05 '19 at 14:41

1 Answers1

1

Taking into account efficiency, running bc for each floating point calculation is not recommended. Consider instead using a different tool (e.g., awk, but possibly Perl or Python) for this task.

Alternative 1: Using awk

awk '
{
    x = $1 ; y=$2 ; z=$3
    r = sqrt(x*x+y*y)
    theta= atan2(y, x)
    printf "%s %s %s %.3f %.3f\n", x, y, z, r, theta
}' TP_xyz.dat > rTh.dat
dash-o
  • 13,723
  • 1
  • 10
  • 37