|
| 1 | +# Maclaurin series approximation of sine |
| 2 | +from math import factorial |
| 3 | + |
| 4 | + |
| 5 | +def maclaurin_sin(theta, accuracy=30): |
| 6 | + """ |
| 7 | + Returns the maclaurin approximation of sine |
| 8 | + :param theta: the angle to which sin is found |
| 9 | + :param accuracy: the degree of accuracy wanted minimum ~ 1.5 theta |
| 10 | + :return: the value of sine in radians |
| 11 | +
|
| 12 | +
|
| 13 | + >>> maclaurin_sin(10) |
| 14 | + -0.54402111088927 |
| 15 | + >>> maclaurin_sin(-10) |
| 16 | + 0.54402111088927 |
| 17 | + >>> maclaurin_sin(10, 15) |
| 18 | + -0.5429111519640644 |
| 19 | + >>> maclaurin_sin(-10, 15) |
| 20 | + 0.5429111519640644 |
| 21 | + >>> maclaurin_sin("10") |
| 22 | + Traceback (most recent call last): |
| 23 | + ... |
| 24 | + ValueError: maclaurin_sin() requires an int or float value for theta and positive int for accuracy |
| 25 | + >>> maclaurin_sin(10, -30) |
| 26 | + Traceback (most recent call last): |
| 27 | + ... |
| 28 | + ValueError: maclaurin_sin() requires an int or float value for theta and positive int for accuracy |
| 29 | + >>> maclaurin_sin(10, 30.5) |
| 30 | + Traceback (most recent call last): |
| 31 | + ... |
| 32 | + ValueError: maclaurin_sin() requires an int or float value for theta and positive int for accuracy |
| 33 | + >>> maclaurin_sin(10, "30") |
| 34 | + Traceback (most recent call last): |
| 35 | + ... |
| 36 | + ValueError: maclaurin_sin() requires an int or float value for theta and positive int for accuracy |
| 37 | + """ |
| 38 | + |
| 39 | + if not isinstance(accuracy, int) or accuracy <= 0 or type(theta) not in [int, float]: |
| 40 | + raise ValueError('maclaurin_sin() requires an int or float value for theta and positive int for accuracy') |
| 41 | + |
| 42 | + theta = float(theta) |
| 43 | + |
| 44 | + _total = 0 |
| 45 | + for r in range(accuracy): |
| 46 | + _total += ((-1)**r)*((theta**(2*r+1))/(factorial(2*r+1))) |
| 47 | + return _total |
| 48 | + |
| 49 | + |
| 50 | +if __name__ == "__main__": |
| 51 | + print(maclaurin_sin(10)) |
| 52 | + print(maclaurin_sin(-10)) |
| 53 | + print(maclaurin_sin(10, 15)) |
| 54 | + print(maclaurin_sin(-10, 15)) |
| 55 | + print(maclaurin_sin("10")) |
| 56 | + print(maclaurin_sin(10, -30)) |
| 57 | + print(maclaurin_sin(10, 30.5)) |
| 58 | + print(maclaurin_sin(10, "30")) |
0 commit comments