YouTip LogoYouTip

Ref Math Cos

## Python math.cos() Method The `math.cos()` method is a built-in function in Python's standard `math` module. It returns the cosine of a given angle expressed in radians. --- ### Introduction In trigonometry, the cosine of an angle in a right-angled triangle is the ratio of the length of the adjacent side to the length of the hypotenuse. The `math.cos(x)` method calculates this value for an angle `x` (in radians). * **Python Version Added:** 1.4 * **Domain:** $[-1.0, 1.0]$ (The returned float value will always be between -1 and 1, inclusive). --- ### Syntax To use the `math.cos()` method, you must first import the `math` module: ```python import math math.cos(x) ``` #### Parameters | Parameter | Type | Description | | :--- | :--- | :--- | | **x** | `float` or `int` | **Required.** A numeric value representing the angle in **radians**. | #### Return Value * **Type:** `float` * **Description:** Returns a floating-point value between `-1.0` and `1.0` representing the cosine of the angle `x`. #### Exceptions * If `x` is not a number (e.g., a string or a list), the method raises a `TypeError`. --- ### Code Examples #### Basic Usage The following example demonstrates how to calculate the cosine of various values: ```python import math # Calculate cosine for different values print(math.cos(0.00)) # Cosine of 0 print(math.cos(-1.23)) # Cosine of a negative number print(math.cos(10)) # Cosine of an integer print(math.cos(3.14159265359)) # Cosine of Pi (approximate) ``` **Output:** ```text 1.0 0.3342377271245026 -0.8390715290764524 -1.0 ``` --- ### Considerations & Common Workflows #### 1. Converting Degrees to Radians Because `math.cos()` expects the input angle to be in **radians**, passing degrees directly will yield incorrect results. You must convert degrees to radians first using either: * `math.radians(degrees)` * The mathematical formula: $\text{radians} = \text{degrees} \times \frac{\pi}{180}$ ```python import math degrees = 60 # Method 1: Using math.radians() radians_1 = math.radians(degrees) print(f"Cosine of 60 degrees: {math.cos(radians_1)}") # Expected: ~0.5 # Method 2: Manual conversion using math.pi radians_2 = degrees * (math.pi / 180) print(f"Cosine of 60 degrees (manual): {math.cos(radians_2)}") ``` **Output:** ```text Cosine of 60 degrees: 0.5000000000000001 Cosine of 60 degrees (manual): 0.5000000000000001 ``` *(Note: Due to floating-point precision limitations, the output may be extremely close to `0.5` rather than exactly `0.5`.)* #### 2. Handling Type Errors If you pass a non-numeric value to the function, Python will raise a `TypeError`: ```python import math try: math.cos("90") except TypeError as e: print(f"Error: {e}") ``` **Output:** ```text Error: must be real number, not str ```
← Ref Math CoshRef Math Atan2 β†’