Home Communities
IT Knowledge
Inspiration
Languages
EN

# Python - math.cos() method example

0 points
Created by:
394

The math.cos() function returns the cosine of the specified angle in radians in the range -1 to +1.

import math

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

print(math.cos( -1.5707963267948966) )  # ~0  <- ~-90 degrees == -pi / 2

Note: 6.123233995736766e-17, -1.8369701987210297e-16 and 6.123233995736766e-17 should be equal to 0 but they are not because of computation precision error.

## 1. Documentation

 Syntax math.cos(number) Parameters number - double value in radians. Result returns a numeric value between -1 and +1, which represents the cosine of the angle. Description cos is a method that takes only one parameter and returns an approximation of cos(x) mathematical function result.

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:

## 3. Working with degrees

import math

def calculate_cos(deg):
rad = (math.pi / 180) * deg

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_cos(deg)
print("cos(", deg, " deg) = ", y)
deg += dx

Output:

cos( 0.0  deg) =  1.0
cos( 15.0  deg) =  0.9659258262890683
cos( 30.0  deg) =  0.8660254037844387
cos( 45.0  deg) =  0.7071067811865476
cos( 60.0  deg) =  0.5000000000000001
cos( 75.0  deg) =  0.25881904510252074
cos( 90.0  deg) =  6.123233995736766e-17

## 4. Reversed console plot example

import math

x1 = 0.0         # beginning of cosine chart
x2 = 3 * 3.14    # end of cosine chart

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

y1 = 0.0

string = ""

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

print(string, "+")

Output:

+
+
+
+
+
+
+
+
+
+
+
+

## References

1. Cosine - Wikipedia

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