[pgsql-jp: 27713] Re: float4を使った計算について

KaWaZ kawaz-pgsql-jp=sra.co.jp @ 7cho-me.com
2002年 10月 22日 (火) 12:44:10 JST


河津です。

>ロス率を含めた合計数を求めたいと思っていますが、フィールドにfloat4を
>使った計算結果が期待した値にならないのはなぜかを教えていただけますで
>しょうか。
>f1が数量、f2がロス率としています。
>
>postgres=# create table test(f1 float4,f2 float4);
>CREATE
>postgres=# insert into test values(1.2,5);
>INSERT 38183619 1
>postgres=# insert into test values(0.7,0);
>INSERT 38183623 1
>postgres=# insert into test values(1.5,0);
>INSERT 38183624 1
>postgres=# insert into test values(1.2,1.1);
>INSERT 38183625 1
>postgres=# create view test_view as select f1,f2,f1*f2/100 as f3 from test;
>CREATE
>postgres=# select f1,f2,f3,f1+f3 as total from test_view;
> f1  | f2  |         f3         |       total
>-----+-----+--------------------+-------------------
> 1.2 |   5 |               0.06 |  1.26000004768372
> 0.7 |   0 |                  0 | 0.699999988079071
> 1.5 |   0 |                  0 |               1.5
> 1.2 | 1.1 | 0.0132000005245209 |  1.21320004820824
>
>
>そもそもfloat4はこのように使うべきでないのでしょうか。

10進数と2進数の相互変換に関する問題です。
説明しているサイトをざっと検索してみました。
以下のページの説明を読めば原因の詳細が分かると思います。
http://www.geocities.co.jp/SiliconValley/4334/unibon/topic/radixerror.html

こういった演算誤差を回避するには、
初めから10進数で内部処理を行う decimal 型を使うことをお勧めします。

-------------------------
KaWaZ <kawaz @ 7cho-me.com>
http://www.kawaz.jp/



pgsql-jp メーリングリストの案内