0

I have a query where in, I need to find the exp of a number. In some cases, the exp is too huge returning an overflow error or in some cases, the argument for function exp is too huge. In those cases I need to return some arbitrary value.

Example (which does not work)

select LEAST(exp(1000), 1::double precision);

Here, I attempt to find the exp(1000). If it is too huge, I return 1.

How can I do this in Postgres?

1 Answer 1

0

Something like this:

create or replace function safe_exp(val double precision)
  returns double precision
  language plpgsql
as
$body$
declare
  result double precision;
begin
  begin
    result := exp(val);
  exception 
    when others then 
      result := 1.0;
  end;
  return result;
end;
$body$

But due to the exception block this will be slower than a "regular" exp() call.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.