在PostgreSQL中发生下溢错误时是否有解决方法?

时间:2015-12-03 20:17:29

标签: postgresql underflow

我有一个表,每行包含a,b和c参数到以下公式中的指数曲线:

a*exp(-b*x)+c

所有列都是double precision类型。 我希望以x的特定值对每条曲线进行采样,并将其值记录在新列中。但是,这样做会导致下溢错误。

>update curve_by_wkt set samplepoint05 = a*exp(-b*0.05)+c;
ERROR:  value out of range: underflow

我无法手动检查a,b,c的哪些值导致计算失败。我所知道的是,不需要极高的精度,超出一定范围的值可能无关紧要。

我想知道是否有任何方法可以让计算完成,因为我无视精确度。

由于

2 个答案:

答案 0 :(得分:1)

创建一个函数并捕获异常。您可以提出自己的错误消息:

Mapper.CreateMap<Common.BookList, Book>().IgnoreAllNonExisting();
Mapper.CreateMap<Common.Categories, Categories>().IgnoreAllNonExisting();
Mapper.AssertConfigurationIsValid();

或设置一些默认值:

create or replace function calculate_with_error
    (a double precision, b double precision, c double precision, x double precision)
returns double precision language plpgsql as $$
begin
    return a * exp(-b * x) + c;
    exception when numeric_value_out_of_range then 
        raise exception 'Value out of range for a = % b= % c= % x= %', a, b, c, x;
end $$;

select calculate_with_error(1, 1, 0, 10000);

ERROR:  Value out of range for a = 1 b= 1 c= 0 x= 10000

用法:

create or replace function calculate_with_default
    (a double precision, b double precision, c double precision, x double precision)
returns double precision language plpgsql as $$
begin
    return a * exp(-b * x) + c;
    exception when numeric_value_out_of_range then 
        return 0;
end $$;

select calculate_with_default(1, 1, 0, 10000);

 calculate_with_default 
------------------------
                      0
(1 row)

答案 1 :(得分:-1)

更好的解决方案(最有可能)是使用greatest函数来设置最小值。例如,

 greatest(a*exp(-b*x)+c, -50)

大部分时间0或一些任意低的数字都足够好。