Search code examples
pythonmathtrigonometryfractionssymbolic-math

Using Python to create a Unit Circle calculator?


As a younger programmer, I'm always trying to look for applications of my skills.

Anyways, I'm currently taking trig and we're working on unit circles, the formula for converting from degrees to a coordinate is (sinθ, cosθ) (to the best of my knowledge).

However, the difficulty I'm having is that I need to keep the values as fractions.

Basically, the algorithm I've planned is:

i = 0
while i < 360:
    print(i, "=", calc(i))
    i += 15

Now, calc can be given any name, and will be a function that returns a coordinate (probably as a tuple) of x and y given x = sin θ and y = cos θ.

The issue I'm having is that sin in Python returns a floating point between -1 and 1, however, I need to find a way to have it return a fraction. For example, in this picture the coordinates are rational numbers.

What should I do? Should I write my own sine and cosine functions, and if so, how should I do that?


Solution

  • It looks like you need a third-party module such as sympy:

    >>> import sympy
    >>> for i in range(0, 360, 15):
    ...     print i, sympy.sin(sympy.Rational(i, 180) * sympy.pi)
    ...
    
    0 0
    15 sin(pi/12)
    30 1/2
    45 2**(1/2)/2
    60 3**(1/2)/2
    75 sin(5*pi/12)
    90 1
    105 sin(5*pi/12)
    120 3**(1/2)/2
    135 2**(1/2)/2
    150 1/2
    165 sin(pi/12)
    180 0
    195 -sin(pi/12)
    210 -1/2
    225 -2**(1/2)/2
    240 -3**(1/2)/2
    255 -sin(5*pi/12)
    270 -1
    285 -sin(5*pi/12)
    300 -3**(1/2)/2
    315 -2**(1/2)/2
    330 -1/2
    345 -sin(pi/12)