Ref Math Fabs
## Python math.fabs() Method
The `math.fabs()` method is a built-in function in Python's standard `math` module that returns the absolute value of a number.
An absolute value represents the non-negative magnitude of a real number, effectively removing any negative sign. Unlike Python's built-in `abs()` function, `math.fabs()` always converts the input value and returns the result as a floating-point number (`float`).
---
### Syntax
To use the `math.fabs()` method, you must first import the `math` module:
```python
import math
math.fabs(x)
```
### Parameters
| Parameter | Type | Description |
| :--- | :--- | :--- |
| `x` | Numeric (`int`, `float`) | **Required.** The number for which you want to find the absolute value. |
### Return Value
* **Type:** `float`
* **Description:** Returns the absolute value of the input number `x` as a floating-point value.
* **Exceptions:** Raises a `TypeError` if the input `x` is not a numeric type (e.g., if it is a string or a list).
---
### Code Examples
#### Example 1: Basic Usage with Positive and Negative Numbers
The following example demonstrates how to find the absolute value of various positive and negative floating-point numbers.
```python
import math
# Calculate and print absolute values
print(math.fabs(2.77)) # Output: 2.77
print(math.fabs(8.32)) # Output: 8.32
print(math.fabs(-99.29)) # Output: 99.29
```
**Output:**
```text
2.77
8.32
99.29
```
#### Example 2: Integer Inputs
When you pass an integer to `math.fabs()`, it automatically converts the result to a float.
```python
import math
print(math.fabs(-5)) # Output: 5.0
print(math.fabs(10)) # Output: 10.0
```
**Output:**
```text
5.0
10.0
```
---
### Key Considerations
#### `math.fabs()` vs. Built-in `abs()`
While both functions are used to calculate absolute values, they behave differently in terms of return types and supported data types:
1. **Return Type:**
* `math.fabs(x)` always returns a **float**, regardless of whether the input is an integer or a float.
* The built-in `abs(x)` preserves the original data type. If you pass an integer, it returns an integer; if you pass a float, it returns a float.
2. **Complex Numbers:**
* `math.fabs(x)` **does not support** complex numbers and will raise a `TypeError`.
* The built-in `abs(x)` supports complex numbers and returns their magnitude (hypotenuse): $\sqrt{a^2 + b^2}$.
```python
import math
# Comparison of return types
print(type(abs(-5))) # Output:
print(type(math.fabs(-5))) # Output:
# Complex number handling
z = 3 + 4j
print(abs(z)) # Output: 5.0 (Calculates magnitude)
# print(math.fabs(z)) # Raises TypeError: can't convert complex to float
```
YouTip