Skip to content Skip to sidebar Skip to footer

No Such Acos Function Exists

I've a problem. I want to get the nearest points on google map in android app. Different points/coordinates are stored in sqlite database. And I have to get the nearest 5 from them

Solution 1:

SQLite doesn't support any trigonometric functions by default, so you can't use them in SQL queries.

You can either fetch the list of coordinates and process it in application code, or you can try and expose Java's trigonometric functions in SQLite with user defined functions (see How can I create a user-defined function in SQLite?).

Solution 2:

You can create extension in C that implements trigonometric functions, for example:

/* sql_trig.c */#include"sqlite3ext.h"
SQLITE_EXTENSION_INIT1;
#include<stdlib.h>/* this bit is required to get M_PI out of MS headers */#if defined( _WIN32 )#define _USE_MATH_DEFINES#endif/* _WIN32 */#include<math.h>#define RADIANS(d) (( d / 180.0 ) * M_PI)staticvoidsql_trig_sin( sqlite3_context *ctx, int num_values, sqlite3_value **values ){
    double a = RADIANS(sqlite3_value_double( values[0] ));
    sqlite3_result_double( ctx, sin( a ) );
}

staticvoidsql_trig_cos( sqlite3_context *ctx, int num_values, sqlite3_value **values ){
    double a = RADIANS(sqlite3_value_double( values[0] ));
    sqlite3_result_double( ctx, cos( a ) );
}

staticvoidsql_trig_acos( sqlite3_context *ctx, int num_values, sqlite3_value **values ){
    double a = sqlite3_value_double( values[0] );
    sqlite3_result_double( ctx, acos( a ) );
}

staticvoidsql_trig_radians( sqlite3_context *ctx, int num_values, sqlite3_value **values ){
    sqlite3_result_double( ctx, RADIANS(sqlite3_value_double( values[0] ) ));
}


intsqlite3_extension_init( sqlite3 *db, char **error, const sqlite3_api_routines *api ){
    SQLITE_EXTENSION_INIT2(api);

    sqlite3_create_function( db, "sin",1,
        SQLITE_UTF8, NULL, &sql_trig_sin, NULL, NULL );
    sqlite3_create_function( db, "cos",1,
        SQLITE_UTF8, NULL, &sql_trig_cos, NULL, NULL );
    sqlite3_create_function( db, "acos",1,
        SQLITE_UTF8, NULL, &sql_trig_acos, NULL, NULL );

    return SQLITE_OK;
}

Now you can compile it as a shared library:

$ gcc -c -fPIC sql_trig.c
$ ld -shared -o sql_trig.so sql_trig.o -lm

and load it with SELECT load_extension('./sql_trig.so')

Post a Comment for "No Such Acos Function Exists"