One of the benefits of using the Python programming language is that it is easy to learn, understand and implement. It's portable in that it works equally well on all computer platforms, it's easy to use and it doesn't have the same syntax rules that lower-level languages such as C and C++ have. Use Python to help you solve everyday math problems, such as converting a set of polar coordinates to Cartesian coordinates.
Import the math module into your Python script. At the beginning of the script, add the following:
from math import *
The difference between the two is the way functions will be called in your program later. In the first example, to print the sin of "x," type:
In the second example, type:
Obtain the polar coordinates from the user:
r = raw_input("Please enter the r coordinate: ")
theta = raw_input("Please enter the theta coordinate: ")
Use the conversion formulas to convert "r" and "theta" to "x" and "y":
x = r * cos(theta)
y = r * sin(theta)
Output the results:
print "The Cartesian coordinates for (",r,",",theta,") are (",x,",",y,")"
Another way of formatting it is as follows:
print "The Cartesian coordinates for (%s,%s) are (%s,%s)" % (r, theta, x, y)
Make sure you import the math module. Without it, the Python interpreter will return an error at the cos and sin functions.
Tips and warnings
- Make sure you import the math module. Without it, the Python interpreter will return an error at the cos and sin functions.