YouTip LogoYouTip

Ref Math Fmod

## Python math.fmod() Method The `math.fmod()` method is a built-in function in Python's standard `math` module. It is used to calculate and return the floating-point remainder of the division of two numbers ($x / y$). Unlike the standard Python modulo operator `%`, `math.fmod()` is specifically designed to work with floating-point numbers according to the platform's C library implementation (the standard platform `fmod()` function). --- ### Syntax To use this method, you must first import the `math` module: ```python import math math.fmod(x, y) ``` ### Parameters | Parameter | Type | Description | | :--- | :--- | :--- | | **`x`** | `int` or `float` | **Required.** The dividend (the number to be divided). Must be a numeric value. | | **`y`** | `int` or `float` | **Required.** The divisor (the number to divide by). Must be a non-zero numeric value. | ### Return Value * **Type:** `float` * **Description:** Returns the floating-point remainder of $x / y$. ### Exceptions * **`ValueError`**: Raised if $y$ is `0` (or if both $x$ and $y$ are `0`). * **`TypeError`**: Raised if either $x$ or $y$ is not a numeric value (e.g., a string or list). --- ### Code Examples The following example demonstrates how to use `math.fmod()` with positive numbers, negative numbers, and how it handles errors when dividing by zero. ```python import math # 1. Basic remainder calculations print(math.fmod(20, 4)) # Output: 0.0 print(math.fmod(20, 3)) # Output: 2.0 print(math.fmod(15, 6)) # Output: 3.0 # 2. Working with negative numbers print(math.fmod(-10, 3)) # Output: -1.0 # 3. Division by zero raises a ValueError try: print(math.fmod(0, 0)) except ValueError as e: print(f"ValueError: {e}") ``` **Output:** ```text 0.0 2.0 3.0 -1.0 ValueError: math domain error ``` --- ### Important Considerations #### 1. `math.fmod(x, y)` vs. the `%` Operator While both `math.fmod(x, y)` and `x % y` calculate the remainder of a division, they behave differentlyβ€”especially when dealing with negative numbers: * **Sign of the Result:** * `math.fmod(x, y)` returns a result with the **same sign as the dividend ($x$)**. * The Python `%` operator returns a result with the **same sign as the divisor ($y$)**. * **Precision:** * `math.fmod()` is generally preferred when working with float values because it avoids the precision loss that can sometimes occur with the `%` operator on floats. * Python's `%` operator is typically preferred for integer arithmetic. #### Comparison Table: | Expression | `math.fmod(x, y)` | `x % y` | Reason | | :--- | :--- | :--- | :--- | | `math.fmod(-10, 3)` vs `-10 % 3` | **`-1.0`** | **`2`** | `fmod` takes the sign of $x$ (`-10`); `%` takes the sign of $y$ (`3`). | | `math.fmod(10, -3)` vs `10 % -3` | **`1.0`** | **`-2`** | `fmod` takes the sign of $x$ (`10`); `%` takes the sign of $y$ (`-3`). |
← Ref Math FsumRef Math Exp β†’