python为什么以及如何截断数字数据? [英] Why and how does python truncate numerical data?

查看:491
本文介绍了python为什么以及如何截断数字数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里处理两个变量,但感到困惑,因为当我想按原样将其作为URL参数发送时,它们的值似乎在变化(它们的精度很低).

Am dealing with two variables here, but confused because their values seem to be changing (they loose precision) when I want to send them as URL parameters as they are.

在我从python解释器中重现此情况时,请看一下这种情况:

Look at this scenario as I reproduce it here from the python interpreter:

>>> lat = 0.33245794180134
>>> long = 32.57355093956
>>> lat
0.33245794180133997
>>> long
32.57355093956
>>> nl = str(lat)
>>> nl '0.332457941801'
>>> nlo = str(long)
>>> nlo '32.5735509396'

那是怎么回事?以及如何确保将latlong序列化为字符串并将它们作为url的查询字符串的一部分发送时,我不会失去它们的精确度?

So what is happening? and how can I ensure that when I serialize lat and long to strings and send them as part of a url's query string I don't lose their exact precision?

要澄清这种情况:

  1. 数据最初是从另一个模块(通过集合创建)中的浮点数(在集合中)到达我的模块的.
  2. 精度在这里是一个敏感的问题,因为该数据用于跟踪和监视排序,错误的值可能会导致误报或不必要的警报.
  3. 如果不将数据序列化为字符串(因此我可以将它们作为参数放置在查询字符串中),就无法将数据发送到目标引擎(通过宁静的api进行侦听)

因此,我需要的是将浮点数转换为字符串的最佳方法,同时尽可能减少精度/信息损失.

So what I needed was the best way to transform floats into strings with minimal loss of precision / information.

推荐答案

通常,如果使用'%.14f' % lat,则表示 LOSING PRECISION .

In general if you use '%.14f' % lat, you are LOSING PRECISION.

要使用浮点数获得全精度,请使用repr().

To get full precision from a float, use repr().

示例:

>>> lat = 1/3.
>>> lat
0.3333333333333333
>>> str(lat).count('3')
12
>>> ('%.14f' % lat).count('3')
14
>>> repr(lat).count('3')
16
>>>

顺便说一句,您正在使用旧的Python.

By the way, you are using an old Python.

>>> 0.33245794180134 == 0.33245794180133997
True
>>>

2.7之前的Python使用17个有效十进制数字产生repr(a_float),因为这将保证float(repr(a_float)) == a_float.新方法是使用将提供相同保证的最小位数.跟随此链接,然后按Ctrl-F搜索repr().

Pythons before 2.7 produce repr(a_float) by using 17 significant decimal digits because that will guarantee that float(repr(a_float)) == a_float. The new method is to use the smallest number of digits that will provide the same guarantee. Follow this link and Ctrl-F search for repr().

如果您是从外部来源获得这些数字,则可能会通过浮动这些数字,然后以14个十进制精度的数字对它们进行序列化而失去精度.

If you are getting those numbers from an external source, then you could be losing precision by floating them and then serialising them with 14 decimal digits of precision.

如果要通过计算获得这些数字,则可能会用14位精度的十进制数字序列化它们,从而失去精度.

If you are getting those numbers by calculation, then you could be losing precision by serialising them with 14 decimal digits of precision.

摘要:通常,如果您使用'%.14f'%lat,则会失去精度-不是Python,不是浮点算术,就是您.

Summary: In general if you use '%.14f' % lat, YOU are losing precision -- not Python, not floating-point arithmetic, it's you..

这篇关于python为什么以及如何截断数字数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆