Skip to content

Add sin function to /maths #5949

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
May 16, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions maths/sin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
"""
Calculate sin function.

It's not a perfect function so I am rounding the result to 10 decimal places by default.

Formula: sin(x) = x - x^3/3! + x^5/5! - x^7/7! + ...
Where: x = angle in randians.

Source:
https://www.homeschoolmath.net/teaching/sine_calculator.php

"""

from math import factorial, radians


def sin(
angle_in_degrees: float, accuracy: int = 18, rounded_values_count: int = 10
) -> float:
"""
Implement sin function.

>>> sin(0.0)
0.0
>>> sin(90.0)
1.0
>>> sin(180.0)
0.0
>>> sin(270.0)
-1.0
>>> sin(0.68)
0.0118679603
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

but this seems to be incorrect? sin(0.68) = 0.628793

Copy link
Contributor Author

@zefr0x zefr0x May 12, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The math.sin function in python accepts an angle measured in radians, but my sin function accepts an angle measured in degrees.

If you tested that with math.sin function, do like this to get the right result:

>>> import math
>>> math.sin(math.radians(0.68))
0.011867960298537237

>>> sin(1.97)
0.0343762121
>>> sin(64.0)
0.8987940463
>>> sin(9999.0)
-0.9876883406
>>> sin(-689.0)
0.5150380749
>>> sin(89.7)
0.9999862922
"""
# Simplify the angle to be between 360 and -360 degrees.
angle_in_degrees = angle_in_degrees - ((angle_in_degrees // 360.0) * 360.0)

# Converting from degrees to radians
angle_in_radians = radians(angle_in_degrees)

result = angle_in_radians
a = 3
b = -1

for _ in range(accuracy):
result += (b * (angle_in_radians**a)) / factorial(a)

b = -b # One positive term and the next will be negative and so on...
a += 2 # Increased by 2 for every term.

return round(result, rounded_values_count)


if __name__ == "__main__":
__import__("doctest").testmod()