Skip to content

Commit 257bb32

Browse files
authored
improved function accuracy and added test case
1 parent 0507353 commit 257bb32

File tree

1 file changed

+22
-8
lines changed

1 file changed

+22
-8
lines changed

maths/maclaurin_sin.py

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"""
22
https://en.wikipedia.org/wiki/Taylor_series#Trigonometric_functions
33
"""
4-
from math import factorial
4+
from math import factorial, pi
55

66

77
def maclaurin_sin(theta: float, accuracy: int = 30) -> float:
@@ -12,14 +12,18 @@ def maclaurin_sin(theta: float, accuracy: int = 30) -> float:
1212
:param accuracy: the degree of accuracy wanted minimum ~ 1.5 theta
1313
:return: the value of sine in radians
1414
15+
16+
>>> from math import isclose, sin
17+
>>> all(isclose(maclaurin_sin(x, 50), sin(x)) for x in range(-25, 25))
18+
True
1519
>>> maclaurin_sin(10)
16-
-0.54402111088927
20+
-0.544021110889369
1721
>>> maclaurin_sin(-10)
18-
0.54402111088927
22+
0.5440211108893703
1923
>>> maclaurin_sin(10, 15)
20-
-0.5429111519640644
24+
-0.5440211108893689
2125
>>> maclaurin_sin(-10, 15)
22-
0.5429111519640644
26+
0.5440211108893703
2327
>>> maclaurin_sin("10")
2428
Traceback (most recent call last):
2529
...
@@ -39,18 +43,28 @@ def maclaurin_sin(theta: float, accuracy: int = 30) -> float:
3943
"""
4044

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

4450
if not isinstance(accuracy, int) or accuracy <= 0:
45-
raise ValueError("maclaurin_sin() requires a positive int for accuracy")
51+
raise ValueError(
52+
"maclaurin_sin() requires a positive int for accuracy"
53+
)
4654

4755
theta = float(theta)
4856

57+
div = theta // (2 * pi)
58+
theta = theta - (2 * div * pi)
59+
4960
total = 0
5061
for r in range(accuracy):
5162
total += ((-1) ** r) * ((theta ** (2 * r + 1)) / (factorial(2 * r + 1)))
52-
return float(total)
63+
return total
5364

5465

5566
if __name__ == "__main__":
67+
print(maclaurin_sin(10))
68+
print(maclaurin_sin(-10))
5669
print(maclaurin_sin(10, 15))
70+
print(maclaurin_sin(-10, 15))

0 commit comments

Comments
 (0)