Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.98.2) (envelope-from ) id 1xD7Nc-00000000KGd-1E6f for pgsql-bugs@arkaria.postgresql.org; Sat, 03 Oct 2026 21:34:52 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.98.2) (envelope-from ) id 1xD7Nb-00000003OyP-1V3C for pgsql-bugs@arkaria.postgresql.org; Sat, 03 Oct 2026 21:34:51 +0000 Received: from makus.postgresql.org ([2001:4800:3e1:1::229]) by malur.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.98.2) (envelope-from ) id 1xD7Nb-00000003OyH-0VmJ for pgsql-bugs@lists.postgresql.org; Sat, 03 Oct 2026 21:34:51 +0000 Received: from sss.pgh.pa.us ([68.162.161.243]) by makus.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.98.2) (envelope-from ) id 1xD7NZ-00000000DPA-1AIH for pgsql-bugs@lists.postgresql.org; Sat, 03 Oct 2026 21:34:50 +0000 Received: from sss1.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.18.1/8.18.1) with ESMTP id 693LYjNG259951; Sat, 3 Oct 2026 17:34:45 -0400 From: Tom Lane To: theshallow27@gmail.com cc: pgsql-bugs@lists.postgresql.org Subject: Re: BUG #19741: `avg(double precision)` overflows on cancelling finite inputs whose mean is representable In-reply-to: <19741-01386c4f17e36788@postgresql.org> References: <19741-01386c4f17e36788@postgresql.org> Comments: In-reply-to PG Bug reporting form message dated "Fri, 02 Oct 2026 22:38:39 -0000" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <259949.1791063285.1@sss.pgh.pa.us> Date: Sat, 03 Oct 2026 17:34:45 -0400 Message-ID: <259950.1791063285@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk PG Bug reporting form writes: > The arithmetic mean of two finite values, `1e154` and `-1e154`, is exactly > zero. PostgreSQL's `avg(double precision)` raises an overflow instead. That happens because avg() shares its transition function "float8_accum" with some other aggregates that require tracking sum(x^2) as well as sum(x); it's the sum(x^2) that overflows. We could avoid it by giving avg() a dedicated function that only counts sum(x) and N ... but I'm skeptical that that's worth the trouble. If you're trying to perform calculations that are as numerically unstable as this example in float8, it's probably mostly garbage-in-garbage-out anyway. If I had to do something like this in float8, I'd probably do select sum(x order by abs(x)) / count(x) from ... to try to reduce roundoff and cancellation error. But we're not going to make the bare aggregate do that. Another answer could be to cast the aggregate input to numeric, though that'll be a good deal slower in its own way. regards, tom lane