PostgreSQL Math Function Error
I'm getting an error from a deterministic PG function that seems dependent based on when I call it in a query.
The function is:
CREATE OR REPLACE FUNCTION ircm(starting_money numeric, value numeric, days numeric)
RETURNS numeric
AS $$
BEGIN
-- Calculate effective interest rate, compounded monthly.
RETURN 12*(pow((value/starting_money),(1./(12.*(days/365.)))) - 1);
END;
$$ LANGUAGE plpgsql;
If I call it in a simple SELECT statement, it works fine:
SELECT ircm(100.00,60.427500643787215,30)
Result: -4.79925436505569765596
However, when I run that exact same call from a different SELECT statement using a subquery:
SELECT
ircm(100.00,m.v::numeric,30) AS result
FROM(
SELECT 60.427500643787215 AS v
) m
I get the error:
ERROR: a negative number raised to a non-integer power yields a complex result
CONTEXT: PL/pgSQL function "ircm" line 6 at RETURN
Since the calls are logically equivalent, how can PG be returning an error for one call, but not the other? I've made sure there's only one definition of the function "ircm" in my database. I've tried dropping/开发者_高级运维adding it again to make sure PG isn't somehow caching a corrupted definition.
Which version and on which platform is your database running?
Have you tried rewriting the function in SQL:
CREATE OR REPLACE FUNCTION ircm(numeric, numeric, numeric)
RETURNS numeric AS $$
select 12 * (pow(($2 / $1), (1. / (12.* ($3 / 365.)))) - 1);
$$ LANGUAGE sql immutable;
I'm running v8.4.4 on Solaris, Linux, and Mac OS X and achieve the same results from your plpgsql (and my SQL) version called directly, and from within the subquery.
精彩评论