Python Glossary Русский

Python 3.13+Numbers & mathfunction

math.fma

product

Fused multiply-add x·y + z with a single rounding (3.13+).

Syntax

math.fma(...)

The whole point is that the intermediate product is never rounded: x*y + z rounds twice and accumulates error across long sums, while fma rounds once. Integer arguments are converted and the result is always a float; in everyday arithmetic the difference is invisible, so reach for it only in numeric code such as dot products or Horner's scheme.

Examples

import math
# math.fma появилась в Python 3.13. На более ранних версиях того же результата
# в большинстве случаев даёт x*y+z — но НЕ всегда: смысл fma в том, что
# умножение и сложение выполняются с одним округлением вместо двух.
fma = getattr(math, 'fma', lambda x, y, z: float(x * y + z))
print(fma(2, 3, 4))      # → 10.0
print(fma(2.5, 4, -1))   # → 9.0
print(fma(0.5, 10, 3))   # → 8.0
print(type(fma(2, 3, 4)))  # → <class 'float'>
import math
# Вот та самая разница в одном округлении. На 3.13+ она видна, на 3.12
# подстановка выше даёт ровно то же выражение, что и справа.
print(fma(0.1, 0.1, -0.01) <= 0.1 * 0.1 - 0.01)  # → ?  (аппаратный fma и порядок округления зависят от платформы)
print(hasattr(math, 'fma'))  # → ?  (появилась в Python 3.13)

See also

Open in the full glossarydocs.python.orgReport an inaccuracy