TheAlgorithms-Python

Форк
0
/
maclaurin_series.py 
123 строки · 3.8 Кб
1
"""
2
https://en.wikipedia.org/wiki/Taylor_series#Trigonometric_functions
3
"""
4

5
from math import factorial, pi
6

7

8
def maclaurin_sin(theta: float, accuracy: int = 30) -> float:
9
    """
10
    Finds the maclaurin approximation of sin
11

12
    :param theta: the angle to which sin is found
13
    :param accuracy: the degree of accuracy wanted minimum
14
    :return: the value of sine in radians
15

16

17
    >>> from math import isclose, sin
18
    >>> all(isclose(maclaurin_sin(x, 50), sin(x)) for x in range(-25, 25))
19
    True
20
    >>> maclaurin_sin(10)
21
    -0.5440211108893691
22
    >>> maclaurin_sin(-10)
23
    0.5440211108893704
24
    >>> maclaurin_sin(10, 15)
25
    -0.544021110889369
26
    >>> maclaurin_sin(-10, 15)
27
    0.5440211108893704
28
    >>> maclaurin_sin("10")
29
    Traceback (most recent call last):
30
        ...
31
    ValueError: maclaurin_sin() requires either an int or float for theta
32
    >>> maclaurin_sin(10, -30)
33
    Traceback (most recent call last):
34
        ...
35
    ValueError: maclaurin_sin() requires a positive int for accuracy
36
    >>> maclaurin_sin(10, 30.5)
37
    Traceback (most recent call last):
38
        ...
39
    ValueError: maclaurin_sin() requires a positive int for accuracy
40
    >>> maclaurin_sin(10, "30")
41
    Traceback (most recent call last):
42
        ...
43
    ValueError: maclaurin_sin() requires a positive int for accuracy
44
    """
45

46
    if not isinstance(theta, (int, float)):
47
        raise ValueError("maclaurin_sin() requires either an int or float for theta")
48

49
    if not isinstance(accuracy, int) or accuracy <= 0:
50
        raise ValueError("maclaurin_sin() requires a positive int for accuracy")
51

52
    theta = float(theta)
53
    div = theta // (2 * pi)
54
    theta -= 2 * div * pi
55
    return sum(
56
        (-1) ** r * theta ** (2 * r + 1) / factorial(2 * r + 1) for r in range(accuracy)
57
    )
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__":
111
    import doctest
112

113
    doctest.testmod()
114

115
    print(maclaurin_sin(10))
116
    print(maclaurin_sin(-10))
117
    print(maclaurin_sin(10, 15))
118
    print(maclaurin_sin(-10, 15))
119

120
    print(maclaurin_cos(5))
121
    print(maclaurin_cos(-5))
122
    print(maclaurin_cos(10, 15))
123
    print(maclaurin_cos(-10, 15))
124

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.