In PostgreSQL I’m getting the error:
ERROR: argument for function "exp" too big
SQL state: 22003
I need to write a stored procedude for the Exponential as:
- If
exp(value)throws argument for function “exp” too big - then return 0
- else return
exp(value)
Please help me how to process this stored procedure.
This is what’s happening:
You’re passing an unrealistically large value to
exp(). It’s way too big to overflow afloat8(double) and can only be represented as aNUMERIC. Even there, there’s a limit, and you hit it when you go aboveexp(5999).For hard maths you might want to try
PL/R, an in-database embedded version of theRlanguage.It’s hard to say what to do, because you haven’t really explained what the query is for, what the inputs to
expare supposed to be, etc.Returning zero for an exponent that’s too big is kind of crazy. Why?
To trap an exception, use BEGIN … EXCEPTION in PL/PgSQL.
I’ve written the below function to return
NaN(“not a number”) instead of zero, as I think returning zero is just downright wrong. Change it if you need to. It might also make a little bit of sense to returnNULL.The error code
numeric_value_out_of_rangewas obtained by looking up theSQLSTATE 22003you get from the out-of-rangeexpin Appendix A. PostgreSQL Error Codes in the Pg manual. You’ll see a link to it in the documentation aboutBEGIN ... EXCEPTION.I initially said that if it’s to be done at all it should be done by testing the input, but I think I was wrong about that. There’s no guarantee that the limit will be
exp(6000), so you’re right to use exception handling even though it’ll be slow and clumsy. I’ll update this response with an exception handling version in a sec.That’s massively more efficient than trapping the “out of range” exception in PL/PgSQL, and makes your intent clearer too.