Skip to content

Commit 80f1da2

Browse files
authored
Add sin function to maths (TheAlgorithms#5949)
* Add sin function to /maths. * Fix typo in /maths/sin.py * Format sin.py to meet the new black rules. * Some improvements. * Fix a formating error.
1 parent dbee5f0 commit 80f1da2

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

maths/sin.py

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
"""
2+
Calculate sin function.
3+
4+
It's not a perfect function so I am rounding the result to 10 decimal places by default.
5+
6+
Formula: sin(x) = x - x^3/3! + x^5/5! - x^7/7! + ...
7+
Where: x = angle in randians.
8+
9+
Source:
10+
https://www.homeschoolmath.net/teaching/sine_calculator.php
11+
12+
"""
13+
14+
from math import factorial, radians
15+
16+
17+
def sin(
18+
angle_in_degrees: float, accuracy: int = 18, rounded_values_count: int = 10
19+
) -> float:
20+
"""
21+
Implement sin function.
22+
23+
>>> sin(0.0)
24+
0.0
25+
>>> sin(90.0)
26+
1.0
27+
>>> sin(180.0)
28+
0.0
29+
>>> sin(270.0)
30+
-1.0
31+
>>> sin(0.68)
32+
0.0118679603
33+
>>> sin(1.97)
34+
0.0343762121
35+
>>> sin(64.0)
36+
0.8987940463
37+
>>> sin(9999.0)
38+
-0.9876883406
39+
>>> sin(-689.0)
40+
0.5150380749
41+
>>> sin(89.7)
42+
0.9999862922
43+
"""
44+
# Simplify the angle to be between 360 and -360 degrees.
45+
angle_in_degrees = angle_in_degrees - ((angle_in_degrees // 360.0) * 360.0)
46+
47+
# Converting from degrees to radians
48+
angle_in_radians = radians(angle_in_degrees)
49+
50+
result = angle_in_radians
51+
a = 3
52+
b = -1
53+
54+
for _ in range(accuracy):
55+
result += (b * (angle_in_radians**a)) / factorial(a)
56+
57+
b = -b # One positive term and the next will be negative and so on...
58+
a += 2 # Increased by 2 for every term.
59+
60+
return round(result, rounded_values_count)
61+
62+
63+
if __name__ == "__main__":
64+
__import__("doctest").testmod()

0 commit comments

Comments
 (0)