Question

We got homework to convert Cartesian Coordinates to Polar Coordinates and I don't even know how to start. So any little help would be nice.

We have to write code in bash. Here is the example that we got:

script.sh 256 128
Result: 286.216 1.107

We have to insert number as parameters and we have to use bc interpreter.

http://linux.die.net/man/1/bc

Was it helpful?

Solution

Because it's your homework, i wrote your program but i put hook into it.My task has some advantages for you:

  1. you can hack bash.
  2. you can hack awk.
  3. you can prevent of math in bash
  4. you can prevent Radian/Degree expression

I only example for call function, unless i complete my program, you see at end of my prog, some call func, it's not my entire main.write a main for it.

My program:

#!/bin/bash

### X and Y 
export x=$1
export y=$2

####calculating r:

export r=`echo "sqrt(x*x+y*y)" |bc -l ` 


####Radian to Degree
r2d(){
    echo "180,3.14156265358979323846,`echo  $1`" |awk ' BEGIN {FS=","} { print $1/$2*$3'} ###HOOK

}
####Degree to Radian
d2r(){

    echo "180,3.14156265358979323846,`echo  $1`" |awk ' BEGIN {FS=","} { print $2/$1*$3'} ###HOOK
}

teta(){
    if [ $x -lt 0 ];then 

        echo `echo "$1,$2" | awk 'BEGIN {FS=","} {print 3.14156265358979323846+atan2($2/$1,1)'}`  ####HOOK
    fi;

    if [ $x  -gt 0 ];then 
        echo `echo "$1,$2" | awk 'BEGIN {FS=","} {print atan2($2/$1,1)'}`  ####HOOK
    fi;
}

echo `r2d 2.09`
echo `d2r 120`
echo `teta $x,$y`

OTHER TIPS

Some tips:

  • use the -l option to bc
  • you'll need the sqrt() and a() functions
  • be clear about which value is "x" and which is "y"
  • use scale=3 to limit the precision
  • bc reads its program from stdin
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top