Python math.fsum() Method



The Python math.fsum() method is used to calculate the sum of an iterable (such as a list or tuple) of floating-point numbers. It mitigates the loss of precision that can occur when adding a large number of floating-point values together using the built-in + operator.

For example, if you have a sequence of floating-point numbers [0.1, 0.2, 0.3], the math.fsum([0.1, 0.2, 0.3]) method will return a more accurate result compared to the standard sum([0.1, 0.2, 0.3]), which might suffer from rounding errors due to the limited precision of floating-point arithmetic.

Syntax

Following is the basic syntax of the Python math.fsum() method −

math.fsum(iterable)

Parameters

This method accepts an iterable (such as a list, tuple, or any other iterable object) containing floating-point numbers as a parameter for which you want to calculate the sum.

Return Value

The method returns a float, which represents the sum of the numbers in the iterable.

Example 1

In the following example, we are calculating the sum of numbers "[0.1, 0.2, 0.3]" using the math.fsum() method −

import math
numbers = [0.1, 0.2, 0.3]
result = math.fsum(numbers)
print("The result obtained is:",result)  

Output

The output obtained is as follows −

The result obtained is: 0.6

Example 2

Here, we are using a generator expression to generate numbers 0.1/i for i ranging from "1 to 5". We then calculate the sum of these numbers using the math.fsum() method −

import math
numbers = (0.1 / i for i in range(1, 6))
result = math.fsum(numbers)
print("The result obtained is:",result)  

Output

Following is the output of the above code −

The result obtained is: 0.22833333333333333

Example 3

If we pass integers as an argument to the fsum() method, it returns a floating-point number −

import math
numbers = [1, 2, 3, 4, 5]
result = math.fsum(numbers)
print("The result obtained is:",result)  

Output

We get the output as shown below −

The result obtained is: 15.0

Example 4

In this example, we calculate the sum of an empty list using the math.fsum() method −

import math
numbers = []
result = math.fsum(numbers)
print("The result obtained is:",result)  

Output

The result produced is as shown below −

The result obtained is: 0.0
python_maths.htm
Advertisements