math.fsum

Full name
math.fsum
Library
math
Syntax

math.fsum(iterable)

Description

The math.fsum function returns the precise sum of the values of the iterable that it receives as an argument. Loss of precision is avoided by using multiple partial sums.

Parameters
  • iterable: iterable whose elements we want to add.
Result

The result returned by the math.fsum function is a real number.

Examples

We can obtain the sum of an iterable formed by the integers 2, 4 and 1 with the following code:

math.fsum([2, 4, 1])

7.0

Note that the returned result is a real number even though the elements of the iterable are integers.

There are circumstances in which the integrated sum function can return an imprecise result. For example, if we start from the following iterable composed of 10 values 0.1 (whose sum is 1):

a = [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]

...applying the sum function we obtain the following result:

sum(a)

0.9999999999999999

On the other hand, the math.fsum function gives the correct result:

math.fsum(a)

1.0

Submitted by admin on Wed, 01/20/2021 - 13:59