Received: from maia.hub.org (maia-3.hub.org [200.46.204.243]) by mail.postgresql.org (Postfix) with ESMTP id A27051337C19 for ; Wed, 13 Apr 2011 14:55:58 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.243]) (amavisd-maia, port 10024) with ESMTP id 59527-01-5 for ; Wed, 13 Apr 2011 17:55:51 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from sss.pgh.pa.us (sss.pgh.pa.us [66.207.139.130]) by mail.postgresql.org (Postfix) with ESMTP id 458A31337C0F for ; Wed, 13 Apr 2011 14:55:01 -0300 (ADT) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.2/8.14.2) with ESMTP id p3DHt0Ve009076; Wed, 13 Apr 2011 13:55:00 -0400 (EDT) To: "John Dickson" cc: pgsql-bugs@postgresql.org Subject: Re: BUG #5975: Incorrect result from mod function with cast In-reply-to: <201104130030.p3D0UCSZ076614@wwwmaster.postgresql.org> References: <201104130030.p3D0UCSZ076614@wwwmaster.postgresql.org> Comments: In-reply-to "John Dickson" message dated "Wed, 13 Apr 2011 00:30:12 +0000" Date: Wed, 13 Apr 2011 13:55:00 -0400 Message-ID: <9075.1302717300@sss.pgh.pa.us> From: Tom Lane X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-1.91 tagged_above=-5 required=5 tests=BAYES_00=-1.9, T_RP_MATCHES_RCVD=-0.01 X-Spam-Level: X-Archive-Number: 201104/78 X-Sequence-Number: 29997 "John Dickson" writes: > The following SQL (executed on 8.3.11) shows a result one higher than the > maximum permissible remainder when combined with a cast: > select 1129590 % 66, > cast(1129590 as numeric(21, 0)) % 66; > ?column? | ?column? > ----------+---------- > 0 | 66 This is basically a roundoff issue. It's fixed in 8.4 and up, as a result of this patch: Author: Tom Lane Branch: master Release: REL8_4_BR [a0fad9762] 2008-04-04 18:45:36 +0000 Re-implement division for numeric values using the traditional "schoolbook" algorithm. This is a good deal slower than our old roundoff-error-prone code for long inputs, so we keep the old code for use in the transcendental functions, where everything is approximate anyway. Also create a user-accessible function div(numeric, numeric) to provide access to the exact result of trunc(x/y) --- since the regular numeric / operator will round off its result, simply computing that expression in SQL doesn't reliably give the desired answer. This fixes bug #3387 and various related corner cases, and improves the usefulness of PG for high-precision integer arithmetic. We felt at the time that it was inappropriate to back-patch such a behavioral change, and I doubt that decision is going to change now. I'd suggest considering an update to 8.4 if this is a critical issue for you. regards, tom lane