YouTip LogoYouTip

Ref Math Sqrt

## Python math.sqrt() Method The `math.sqrt()` method is a built-in function in Python's standard `math` module. It is used to calculate and return the square root of a given number. --- ### Syntax To use the `math.sqrt()` method, you must first import the `math` module: ```python import math math.sqrt(x) ``` ### Parameters | Parameter | Type | Description | | :--- | :--- | :--- | | **x** | Numeric (`int` or `float`) | **Required.** The number for which you want to find the square root. | ### Return Value * **Type:** `float` * **Description:** Returns the square root of the specified number `x` as a floating-point number. --- ### Exceptions and Errors The `math.sqrt()` method expects a non-negative real number. Passing invalid arguments will raise the following exceptions: * **`ValueError`**: Raised if `x` is a negative number (less than `0`). * **`TypeError`**: Raised if `x` is not a numeric value (e.g., a string or a list). --- ### Code Examples #### Example 1: Basic Usage The following example demonstrates how to find the square root of positive integers: ```python import math # Calculate and print the square root of various numbers print(math.sqrt(9)) print(math.sqrt(25)) print(math.sqrt(16)) ``` **Output:** ```text 3.0 5.0 4.0 ``` #### Example 2: Working with Floating-Point Numbers The `math.sqrt()` method can also handle decimal values: ```python import math # Calculate the square root of a float print(math.sqrt(2.25)) print(math.sqrt(0.64)) ``` **Output:** ```text 1.5 0.8 ``` #### Example 3: Handling Exceptions This example shows how Python handles negative numbers and non-numeric types when passed to `math.sqrt()`: ```python import math # 1. Passing a negative number raises a ValueError try: math.sqrt(-9) except ValueError as e: print(f"ValueError: {e}") # 2. Passing a string raises a TypeError try: math.sqrt("nine") except TypeError as e: print(f"TypeError: {e}") ``` **Output:** ```text ValueError: math domain error TypeError: must be real number, not str ``` --- ### Important Considerations * **Complex Numbers:** The `math.sqrt()` method cannot handle negative numbers and will raise a `ValueError: math domain error`. If you need to calculate the square root of a negative number (which results in a complex number), use the `cmath.sqrt()` function from Python's complex math module instead: ```python import cmath print(cmath.sqrt(-9)) # Output: 3j ``` * **Alternative Method:** You can also calculate square roots using the exponentiation operator (`**`) by raising a number to the power of `0.5` (e.g., `9 ** 0.5`). However, `math.sqrt()` is generally preferred for readability and performance when working with real numbers.
← Ref Math IsfiniteRef Math Isclose β†’