Skip to content

Commit 59fc97b

Browse files
authored
added maclaurin_sin.py function
1 parent 4829fea commit 59fc97b

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

maths/maclaurin_sin.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
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

Comments
 (0)