Home Communities
IT Knowledge
Inspiration
Languages
EN

# Python - math.sin() method example

0 points
Created by:
350

`math.sin` is a method that takes only one parameter and returns an approximation of sine mathematical function.

``````import math

print(math.sin(0))                    # 0   <-     0 degrees
print(math.sin(1.5707963267948966))   # ~1  <-   ~90 degrees ==  pi / 2
print(math.sin(3.1415926535897932))   # ~0  <-  ~180 degrees ==  pi
print(math.sin(4.71238898038469))     # ~-1 <-  ~270 degrees == -pi * (3/2)
print(math.sin(6.2831853071795850))   # ~0  <-  ~360 degrees ==  pi * 2

print(math.sin(-1.5707963267948966))  # ~-1 <-  ~-90 degrees == -pi / 2``````

Note: `1.2246467991473532e-16` and `-1.133107779529596e-15` should be equal to `0` but they are not because of compuptation precision error.

## 1. Documentation

 Syntax ``math.sin(x)`` Parameters `x` - a number that represents an angle in radians. Result `x` value calculated as `sin(x)` mathematical function in a range `-1` to `+1`. If `x` is not a number, the function returns `TypeError`. If the function can not calculate it returns `ValueError`. Description `sin` is a method that takes only one parameter and returns an approximation of `sin(x)` mathematical function.

``````import math

x1 = 0.0            # beginning of calculation in radians
x2 = math.pi / 2    # ending of calculation radians

dx = math.pi / 9    # calculation step in degrees

Output:

``````sin(0 rad) = 0

## 3. Working with degrees

``````import math

def calculate_sin(deg):
radians = (math.pi / 180) * deg

# Example:
x1 = 0.0   # beginning of calculation in degrees
x2 = 90.0  # ending of calculation degrees

dx = 15.0  # calculation step in degrees

deg = x1
while deg <= x2:
y = calculate_sin(deg)
print("sin(", deg, " deg) = ", y)
deg += dx``````

Output:

``````sin(0 deg) = 0
sin(15 deg) = 0.25881904510252074
sin(30 deg) = 0.49999999999999994
sin(45 deg) = 0.7071067811865476
sin(60 deg) = 0.8660254037844386
sin(75 deg) = 0.9659258262890683
sin(90 deg) = 1``````

## 4. Reversed console plot example

``````import math

x1 = 0.0       # beginning of sine chart
x2 = 2 * 3.14  # end of sine chart

dx = 3.14 / 4.0  # x axis step
dy = 1.0 / 5.0   # y axis step

y1 = 0.0
line = ""

y = y1
while y < y2:
line += " "
y += dy

print(line, "+")

Output:

``````      +
+
+
+
+
+
+
+``````

## References

1. Sine - Wikipedia

Join to our subscribers to be up to date with content, news and offers.