FLP01-C. 浮動小数点式の演算の順序に注意する
浮動小数点式を再構成するときには、演算の順序に注意して結果の精度が最も高くなるようにせよ。
C99 [ISO/IEC 9899:1999] のセクション 5.1.2.3「プログラムの実行」 には、次のように記載されている。
浮動小数点型の式に対する再構成は、しばしば精度と範囲の制約によって制限される。処理系は、たとえオーバフロー及びアンダフローが発生しない場合でも、丸め誤差のために、加算若しくは乗算に対する数学的結合法則、又は数学的分配法則を一般に適用することはできない。さらに、処理系は、一般的に、式の再構成の目的で 10 進定数を置き換えることはできない。次のプログラム片では、実数に対する数学の諸規則の適用による式の再構成は、必ずしも正しいとは限らない。double x, y, z; /* ... */ x = (x * y) * z; /* x *= y * z と等価ではない; */ z = (x - y) + y ; /* z = x と等価ではない; */ z = x + x * y; /* z = x * (1.0 + y) と等価ではない; */ y = x / 5.0; /* y = x * 0.2 と等価ではない; */
リスク評価
浮動小数点形式で表現される数の制限と式の演算の順序による影響を理解していなければ、予期せぬ演算結果を招くことがある。
レコメンデーション | 深刻度 | 可能性 | 修正コスト | 優先度 | レベル |
---|---|---|---|---|---|
FLP01-C | 低 | 中 | 高 | P2 | L3 |
参考情報
- [ISO/IEC 9899:1999] Section 5.1.2.3, "Program execution"
- [ISO/IEC PDTR 24772] "PLF Floating Point Arithmetic"
翻訳元
これは以下のページを翻訳したものです。
FLP01-C. Take care in rearranging floating point expressions