How can I compare a float value in mongodb?

huangapple go评论89阅读模式
英文:

How can I compare a float value in mongodb?

问题

我有一个名为myplace的集合,其中包含place_name(字符串)、latitude(float64)和longitude(float64)字段。现在我有一个纬度为12.34567,我需要在MongoDB中搜索是否存在这个纬度。我尝试了以下方式,但返回的结果是null:

 db.myplace.find({"latitude":12.3456})
英文:

I have a collection name myplace having place_name(string), latitude(float64) and longitude(float64). Now I have a latitude 12.34567, I need to search mongodb is this latitude is present there or not.
I tried like this but its returning null

 db.myplace.find({"latitude":12.3456})

答案1

得分: 4

比较浮点数的相等性通常是一个不好的主意,因为在各种浮点数运算中发生的舍入可能导致你期望相等的值具有稍微不同的值。

更好的解决方案是检查两个浮点数之间的差异是否小于一个特定的误差范围 E。对于这种查询,检查变成了一个范围检查,例如:

12.3456 - E < latitude < 12.3456 + E

此问题所述,可以使用 mgo 表示这种查询:

lat := 12.3456
E := 0.0001
q := c.Find(bson.M{"latitude": bson.M{"$gt": lat - E, "$lt": lat + E}})
英文:

It is generally a bad idea to compare floating point values for equality, since the rounding that occurs in various floating point operations can cause certain values you'd expect to be equal to have slightly different values.

A better solution is to check that the difference between the two floating point values is less than a particular error margin E. For this kind of query, the check becomes a range check e.g. that:

12.3456 - E &lt; latitude &lt; 12.3456 + E

As described in this question, this kind of query can be represented with mgo as:

lat := 12.3456
E := 0.0001
q := c.Find(bson.M{&quot;latitude&quot;: bson.M{&quot;$gt&quot;: lat - E, &quot;$lt&quot;: lat + E}})

答案2

得分: 2

首先,你是在寻找(拥有)12.34567还是要找到12.3456?

浮点数是实数的近似表示。你可以在一个范围内寻找一个数。例如,

(12.34567 - 0.0001) < 纬度 < (12.34567 + 0.0001)

参考资料:

浮点数

英文:

First, are you looking for (have) 12.34567 or (find) 12.3456?

Floating-point numbers are an approximation of real numbers. Look for a number in a range. For example,

(12.34567 - 0.0001) &lt; latitude &lt; (12.34567 + 0.0001)

References:

Floating point

huangapple
  • 本文由 发表于 2014年10月27日 14:56:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/26582442.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定