yohhoyの日記

技術的メモをしていきたい日記

和積演算(FMA)

C99標準ライブラリではデジタル信号処理の定番、和積演算(FMA; fused multiply-add)fma関数が追加されている。同関数はC++11標準ライブラリ<cmath>ヘッダでも提供される。

fma関数では和積演算を単一の演算子として浮動小数点数の丸めを行う。すなわち通常の 乗算→丸め→加算 とは異なる結果となる。

double a, x, y, z;
a = fma(x, y, z);  // x×y+z

JTC1/SC22/WG14 N1256 7.12.13.1より引用。

#include <math.h>
double fma(double x, double y, double z);
float fmaf(float x, float y, float z);
long double fmal(long double x, long double y, long double z);

Description
The fma functions compute (x × y) + z, rounded as one ternary operation: they compute the value (as if) to infinite precision and round once to the result format, according to the current rounding mode. A range error may occur.
Returns
The fma functions return (x × y) + z, rounded as one ternary operation.

FP_FAST_FMAマクロが定義されている場合は、ハードウェア専用命令による高速なFMA実装が利用される*1

*1:"Typically, the FP_FAST_FMA macro is defined if and only if the fma function is implemented directly with a hardware multiply-add instruction."(N1256 7.12/p7 脚注202)