Content · Programming · Python

Python math.fsum() Function: Usage and Examples

Add floating-point values with improved precision.

3 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Add floating-point values with improved precision.

What You Will Learn


fsum(iterable) tracks partial sums to reduce rounding error from a long sequence of floating-point additions. It still returns float, not an exact rational value.

For floating-point results, remember that stored values are approximations. Rounding a displayed value does not change the exact value used by later calculations.

Step-by-Step Example


The example below makes the behavior visible with small input values that you can change safely.

import math
print(math.fsum([0.1] * 10))

How the Example Works


  • The imports provide the standard-library tools used in the demonstration: math.
  • The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.

For the chosen input, the expression math.fsum([0.1] * 10) prints 1.0. This summation reduces rounding error compared with accumulating binary floats naively.

Expected output from the example:

1.0

Another Example: Compare the Results


Try a second input and compare it with the first. Notice whether the result changes in type, value, order, or number of items.

import math
print(math.fsum([0.1] * 10), sum([0.1] * 10))

Expected output:

1.0 1.0

When You Would Use This


This operation can support measurements, numeric reports, simulations, or input validation. Choose integer operations when exact integer answers are required, and check floating-point rounding when displaying measured values. Validate units and input domains before using the result in a calculation.

Practice: Modify the Code


Compare sum() and fsum() over a cancellation-heavy sequence.

Verify the changed output against the behavior described above, including the relevant invalid or boundary case.

For complete parameters and version details, consult the official Python documentation.

Common Beginner Mistakes


  • Assuming improved float summation makes every decimal result mathematically exact.
  • Overlooking this documented constraint: it still returns float, not an exact rational value.

Key Takeaways


  • Add floating-point values with improved precision.
  • fsum(iterable) tracks partial sums to reduce rounding error from a long sequence of floating-point additions.
  • Apply this operation only after checking the assumptions and input conditions shown in the example.
Share this resourceSend this page to someone who may find it useful.