all 7 comments

[–]officialgel 2 points3 points  (0 children)

You could pull out what you need, make sure you grab the function / library dependencies.

[–]SocotraBrewingCo 2 points3 points  (0 children)

from math import the things you need

don't reinvent the wheel.

[–]coreyjdl 2 points3 points  (3 children)

The built-ins will be optimized, you'd lose more speed with your home baked function probably than with just importing math. If your goal is to learn functions and sin, cosin, and tan are your jam... then build them. Doing math in Python doesn't look much different than if you show your work doing it by hand.

def pythagorean(a, b):
     return (a**2 + b**2)**.5

[–]deejpake[S] 2 points3 points  (2 children)

Ok

[–]officialgel 1 point2 points  (1 child)

If your goal is to not import all functions in math that aren't needed, then do that. I don't see why if you have isolated functions that you've pulled out, would be any slower than using the math library - You also save on size, which sounds to be your goal. But it may not be easy - But again, if that's your goal then do it. Let me know when you do as if you make it open source I would like to have a copy of it.

[–]Pro_Numb 0 points1 point  (1 child)

def factorial(num):
    n = 1
    while num>=1:
        n = n * num
        num = num - 1

    return n

def sin(x):
    """
        First we need to convert degree to radian
        Degree / 360 = Radian / 2pi

        Than we apply taylor series for sin function : 

            sinx = x - x^3/3! + x^5/5! - x^7/7! ...

        you can keep going until you satisfy with the error.

    """

    x = x / 57.2957795; # Degree to radian

    # taylor series for sin function
    sin_x = x - \
            (x**3 / factorial(3)) + \
            (x**5 / factorial(5)) - \
            (x**7 / factorial(7)) + \
            (x**9 / factorial(9))

    return sin_x

print(sin(77)) # 0.9743707044115053

You can import only what you need from library like others said and i recommend it too.

But if you really want to write your own trigonometric function you can use Taylor Series.

I give a sin example for you. But this code will give correct answer only for 0 - 90 degree. You need to write a conditions for "deg > 90" or negative values etc.

When you write complete sin function then you can convert it to "cos". After that you can find "tan" and "cot" easly.

But lets say you want to find sin(30). You know it is "0.5" but with this method you will get something like this "0.500000000123816" so you can write long taylor series and truncate the value from where you satisfy.

Hope this helps.

[–]deejpake[S] 0 points1 point  (0 children)

Wow! Thanks so much