Finds the maclaurin approximation of cos :param theta: the angle to which cos is found :param accuracy: the degree of accuracy wanted :return: the value of cosine in radians >>> from math import isclose, cos >>> all(isclose(maclaurin_cos(x, 50), cos(x)) for x in
(theta: float, accuracy: int = 30)
| 58 | |
| 59 | |
| 60 | def maclaurin_cos(theta: float, accuracy: int = 30) -> float: |
| 61 | """ |
| 62 | Finds the maclaurin approximation of cos |
| 63 | |
| 64 | :param theta: the angle to which cos is found |
| 65 | :param accuracy: the degree of accuracy wanted |
| 66 | :return: the value of cosine in radians |
| 67 | |
| 68 | |
| 69 | >>> from math import isclose, cos |
| 70 | >>> all(isclose(maclaurin_cos(x, 50), cos(x)) for x in range(-25, 25)) |
| 71 | True |
| 72 | >>> maclaurin_cos(5) |
| 73 | 0.2836621854632268 |
| 74 | >>> maclaurin_cos(-5) |
| 75 | 0.2836621854632265 |
| 76 | >>> maclaurin_cos(10, 15) |
| 77 | -0.8390715290764524 |
| 78 | >>> maclaurin_cos(-10, 15) |
| 79 | -0.8390715290764521 |
| 80 | >>> maclaurin_cos("10") |
| 81 | Traceback (most recent call last): |
| 82 | ... |
| 83 | ValueError: maclaurin_cos() requires either an int or float for theta |
| 84 | >>> maclaurin_cos(10, -30) |
| 85 | Traceback (most recent call last): |
| 86 | ... |
| 87 | ValueError: maclaurin_cos() requires a positive int for accuracy |
| 88 | >>> maclaurin_cos(10, 30.5) |
| 89 | Traceback (most recent call last): |
| 90 | ... |
| 91 | ValueError: maclaurin_cos() requires a positive int for accuracy |
| 92 | >>> maclaurin_cos(10, "30") |
| 93 | Traceback (most recent call last): |
| 94 | ... |
| 95 | ValueError: maclaurin_cos() requires a positive int for accuracy |
| 96 | """ |
| 97 | |
| 98 | if not isinstance(theta, (int, float)): |
| 99 | raise ValueError("maclaurin_cos() requires either an int or float for theta") |
| 100 | |
| 101 | if not isinstance(accuracy, int) or accuracy <= 0: |
| 102 | raise ValueError("maclaurin_cos() requires a positive int for accuracy") |
| 103 | |
| 104 | theta = float(theta) |
| 105 | div = theta // (2 * pi) |
| 106 | theta -= 2 * div * pi |
| 107 | return sum((-1) ** r * theta ** (2 * r) / factorial(2 * r) for r in range(accuracy)) |
| 108 | |
| 109 | |
| 110 | if __name__ == "__main__": |
no test coverage detected