Ref Math Fsum
## Python math.fsum() Method
The `math.fsum()` method is a built-in function in Python's standard `math` module. It calculates the sum of all elements in an iterable (such as a list, tuple, or array) with high floating-point precision.
Unlike the built-in `sum()` function, `math.fsum()` avoids loss of precision by tracking multiple intermediate partial sums. This makes it the preferred choice when summing floating-point numbers where accuracy is critical.
---
### Syntax
```python
import math
math.fsum(iterable)
```
### Parameters
| Parameter | Type | Description |
| :--- | :--- | :--- |
| `iterable` | Iterable (List, Tuple, Set, etc.) | **Required.** An iterable containing numeric values (integers or floats). |
### Return Value
* **Type:** `float`
* **Description:** Returns the accurate floating-point sum of all elements in the iterable.
### Exceptions
* **`TypeError`**: Raised if the iterable contains non-numeric elements (e.g., strings, dictionary objects, or `None`).
---
### Code Examples
#### Example 1: Basic Usage with Lists of Integers and Floats
```python
import math
# Summing a list of integers
print(math.fsum([1, 2, 3, 4, 5]))
# Summing a list of large integers
print(math.fsum([100, 400, 340, 500]))
# Summing a list of floating-point numbers
print(math.fsum([1.7, 0.3, 1.5, 4.5]))
```
**Output:**
```text
15.0
1340.0
8.0
```
---
### `math.fsum()` vs. Built-in `sum()`
The primary difference between `math.fsum()` and Python's built-in `sum()` is how they handle floating-point arithmetic precision.
Due to the way computers represent floating-point numbers (IEEE 754 standard), adding small and large floats together using standard addition can lead to accumulated rounding errors. `math.fsum()` prevents this by using the Shewchuk algorithm to maintain full precision.
#### Example 2: Precision Comparison
```python
import math
# A list of values where standard float addition fails to maintain precision
values = [0.1] * 10
# Using the built-in sum() function
print("Built-in sum():", sum(values))
# Using math.fsum()
print("math.fsum(): ", math.fsum(values))
```
**Output:**
```text
Built-in sum(): 0.9999999999999999
math.fsum(): 1.0
```
---
### Key Considerations
1. **Always Returns a Float:** Even if the input iterable contains only integers, `math.fsum()` will always return a `float` (e.g., `15.0` instead of `15`).
2. **Performance:** Because `math.fsum()` performs extra steps to guarantee precision, it is slightly slower than the built-in `sum()` function. Use `sum()` for integers or when minor floating-point inaccuracies are acceptable, and reserve `math.fsum()` for precision-critical calculations (e.g., financial or scientific computing).
YouTip