Difference in distance calculation between mongo and google s2

367 views
Skip to first unread message

Dariusz Łuksza

unread,
Dec 22, 2015, 4:13:18 PM12/22/15
to mongodb-user
According to this blog post[1] mongo is using internally google's s2-gemoetry-library (at least in version 2.4). Is this still the case?

The reason I'm asking is that I'm trying to verify results of a complex query that involves distance, date and time calculations. Here is one example where I got different results from s2 java port[2] and mongo.

> db.test.insert({loc: [7.998334555659889, 46.03310986584049], point2: [8.0, 46], distance: 3688, expected: true});
> db.test.ensureIndex({loc: "2dsphere"});

> db.test.find({loc: {$nearSphere: {$geometry: {type: "Point", coordinates: [8.0, 46.0]}, $maxDistance: 3688}}}).length()

0

> db.runCommand({geoNear: 'test', spherical: true, near: {type: "Point" , coordinates: [8.0, 46]}}).results[0].dis

3688.0000000002747


Sample java (pseudo) code:


import com.google.common.geometry.S2LatLng;


public class GeoDistance {


  public static void main(String[] arg) {

    S2LatLng p1 = S2LatLng.fromDegrees(46.03310986584049, 7.998334555659889);

    S2LatLng p2 = S2LatLng.fromDegrees(46, 8);


    System.out.println(p1.getDistance(p2, 6378.1 * 1000)); // this constant is taken from mongo source[3]

  }

}


Prints: 3687.9999999996185


Is this a bug, rounding issue or mongo 3.2 is not using s2 any more for distance calculation?


Any ideas how I can make my test more reliable?

Kevin Adistambha

unread,
Dec 30, 2015, 9:36:24 PM12/30/15
to mongodb-user

Hi Dariusz,

You are correct, MongoDB 3.2 uses S2 for geo calculations for 2dsphere indexes. This is unchanged from when the feature was introduced in 2.4.

The different result that you saw in MongoDB vs. Java test case was likely caused by rounding differences in the floating point implementations of C++ and Java.

Best regards,
Kevin

Reply all
Reply to author
Forward
0 new messages