c......Example 2: Cartesian to spherical polar coordinates convertor
c23456
      program ex2
c
      implicit none
c
      double precision cart(3),polar(3)
      double precision pi
      integer i
c
c..... Assign the value of pi
c
      pi = 3.14159265358979d0
c
c..... Read in the three Cartesian coordinates from the screen
c
      print *, 'Enter (x,y,z) on one line separated by commas'
      read *,cart(1),cart(2),cart(3)
c
c.....The above line can also be written using an implicit do loop
c     read *,(cart(i), i = 1,3)
c
c.....NOTE: There are a variety of ways of converting from Cartesian to
c.....      spherical polar coordinates. The method illustratd below is
c.....      just one.
c
c..... Calculate the r vector
c..... Assign the r vector to polar(1)
c
       polar(1) = sqrt(cart(1)**2+cart(2)**2+cart(3)**2)
c
c..... Calculate the value of theta using the fact that z = r*cos(theta)
c..... Assign theta to polar(2)
c
       polar(2) = acos(cart(3)/polar(1))
c
c..... Calculate the value of phi using the fact that
c..... x = r*sin(theta)*cos(phi)
c
       polar(3) = acos(cart(1)/(polar(1)*sin(polar(2))))
c
c..... Output the results to the keyboard
c
       print *,'Spherical polar coordinates are (angles in radians):'
       print *, ' r = ',polar(1)
       print *, ' theta = ',polar(2)
       print *, ' phi = ',polar(3)
c
c..... Remember that the trigonometric units are by default radians
c..... To convert to degrees you need a value for pi,
c..... Recall: 2*pi radians = 360 degrees
c
       polar(2) = polar(2)/pi*180.0d0
       polar(3) = polar(3)/pi*180.0d0
c
c..... Output the result to the keyboard
c
       print *,'Spherical polar coordinates are (angles in degrees):'
       print *, ' r = ',polar(1)
       print *, ' theta = ',polar(2)
       print *, ' phi = ',polar(3)
c
       end


Return to Fortran Workshop Main Page


This page maintained by alex.brown@ualberta.ca of the Department of Chemistry, University of Alberta

Last updated August 8, 2003.