Well, it’s not the most common function on the block - infact, I’m one of a handful of people who I’ve ever seen use it, but the help that this little blerb will give, will definately not be limited to simply PI(). It’s all about the decimal places. By default mySQL will return PI() as 7 decimal points.
Well, this is fine in general principle, but what about getting really accurate when your dealing with Geo Location’s? Like, finding the distance between two points on the globe? It’s important to get as accurate as you can be when determining these distances! Afterall, the difference between 1km away, and 1.15km away can mean the difference between arriving at a friends and arriving at their neighbors!
Okay, so how do we do it? Well, as I said, PI() returns 7 decimal points, but its easy to change that! You see 7, but mySQL does see more internally because it uses the full double-precision value. Okay, so what does that mean to you? Well, normally it wouldn’t matter, but for some reason I ran across problems with it when working with re-jigging select queries.
Case in point:
SELECT *,(ACOS(COS((’-33.91451667′ * (PI()/180))) * COS((location_lat * (PI()/180))) * COS((’151.1712194′ * (PI()/180))) * COS((location_long * (PI()/180)))+COS((’-33.91451667′ * (PI()/180))) * SIN((’151.1712194′ * (PI()/180))) * COS((location_lat * (PI()/180))) * SIN((location_long * (PI()/180)))+SIN((’-33.91451667′ * (PI()/180))) * SIN((location_lat * (PI()/180)))) * 6378) AS `distance` FROM `maps_location` WHERE 1 ORDER BY `distance` ASC;
Some of the results out of this, were 1km off over a distance of 3200km’s. Not normally a problem for some people, but hey - I’m a perfectionist, so Mark and I sat and wrote an even better query. The trick was, to make PI() think it had more decimals, before sending it in as a variable in the equation, so to do this we simply did:
PI()+0.000000000000000000000
It’s that easy! This will force mySQL to treat this as 22 digit decimal, with the 22,21 logic.
One last thing, another quick way, if your ever stuck in less-logical languages, to get PI() is:
ATAN2(1,1) * 4;
Enjoy.