Search code examples
sqlpostgresqlplpgsqlpostgresql-9.1radians

How to fix input is out of range error in Postgres 9.1


In Postgres 9.1 code below produces error

ERROR:  input is out of range
CONTEXT:  SQL function "gc_dist1" statement 1

How to fix it in 9.1 ?

create or replace function gc_dist1(_lat1 float8, _lon1 float8, _lat2 float8, _lon2 float8) 
returns float8 as $$ 
select ACOS(SIN(radians($1))*SIN(radians($3))+COS(radians($1))*COS(radians($3))*COS(radians($4)-radians($2)))*6371; 
$$ language sql immutable;

select gc_dist1(24.6269989013672,59.3357849157094,24.6269989013672,59.3357849121094);

Solution

  • If fails because acos() function cannot accept value higher that 1. In your example that's the case.

    SELECT  (
            SIN(radians(24.6269989013672))
            * SIN(radians(24.6269989013672))
            + COS(radians(24.6269989013672))
            * COS(radians(24.6269989013672))
            * COS(radians(59.3357849121094)-radians(59.3357849157094))
        ) > 1 -- true
    

    It seems your function logic is incorrect.