Func Number Fabs
## Python math.fabs() Function
In Python, the `math.fabs()` function is used to calculate the absolute value of a number. Unlike the built-in `abs()` function, `math.fabs()` always returns the result as a floating-point number (`float`), even if the input is an integer.
---
## Syntax
To use the `math.fabs()` function, you must first import Python's built-in `math` module.
```python
import math
math.fabs(x)
```
### Parameters
* **`x`**: A numeric value (integer, float, or any numeric expression).
### Return Value
* Returns the absolute value of `x` as a **floating-point number** (`float`).
---
## Code Examples
### Example 1: Basic Usage with Integers and Floats
The following example demonstrates how `math.fabs()` handles both negative and positive numbers, and how it converts integer inputs into floating-point outputs.
```python
import math
# Passing a negative float
x = -1.5
y = math.fabs(x)
print(y) # Output: 1.5
# Passing a positive integer
x = 10
y = math.fabs(x)
print(y) # Output: 10.0
```
**Output:**
```text
1.5
10.0
```
---
### Example 2: Comprehensive Examples
This example demonstrates `math.fabs()` with various numeric types, including floating-point numbers, integers, and mathematical constants like $\pi$ (`math.pi`).
```python
import math
# Calculate absolute values for different numeric types
print("math.fabs(-45.17) : ", math.fabs(-45.17))
print("math.fabs(100.12) : ", math.fabs(100.12))
print("math.fabs(100.72) : ", math.fabs(100.72))
print("math.fabs(119) : ", math.fabs(119))
print("math.fabs(math.pi): ", math.fabs(math.pi))
```
**Output:**
```text
math.fabs(-45.17) : 45.17
math.fabs(100.12) : 100.12
math.fabs(100.72) : 100.72
math.fabs(119) : 119.0
math.fabs(math.pi): 3.141592653589793
```
---
## Key Considerations
### 1. Difference Between `math.fabs()` and Built-in `abs()`
While both functions calculate absolute values, they behave differently regarding return types and supported inputs:
| Feature | `math.fabs(x)` | Built-in `abs(x)` |
| :--- | :--- | :--- |
| **Return Type** | Always returns a `float`. | Returns the same type as the input (e.g., `int` for `int`, `float` for `float`). |
| **Complex Numbers** | Raises a `TypeError`. | Returns the magnitude (modulus) of the complex number as a `float`. |
| **Module Requirement** | Requires `import math`. | Available globally without imports. |
#### Comparison Code:
```python
import math
# Handling Integers
print(type(math.fabs(-5))) # Output: (returns 5.0)
print(type(abs(-5))) # Output: (returns 5)
# Handling Complex Numbers
# abs() works with complex numbers:
print(abs(3 + 4j)) # Output: 5.0
# math.fabs() will raise a TypeError:
# math.fabs(3 + 4j) # TypeError: can't convert complex to float
```
YouTip