python float格式怪异? [英] python float formatting weirdness?

查看:115
本文介绍了python float格式怪异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试调试两个执行非常相似代码的不同python脚本.这些脚本设置a,这是一个简单的浮点数.

I'm trying to debug two different python scripts that execute very similar code. These scripts set a, which is a simple float.

对于脚本1:

ipdb> print sys.version
2.7 (r27:82500, Jul 15 2010, 13:04:38)
[GCC 4.1.2 20071124 (Red Hat 4.1.2-42)]
ipdb> type(a)
<type 'float'>
ipdb> print a
17.23105
ipdb> print '{0:.4f}'.format(a)
17.2311

对于脚本2:

ipdb> print sys.version
2.7 (r27:82500, Jul 15 2010, 13:04:38)
ipdb> print type(a)
<type 'float'>
ipdb> print a
17.23105
ipdb> print '{0:.4f}'.format(a)
17.2310

在两种情况下a如何设置不同的格式?如果我已经检查过17.23105的值是否相同,则两个脚本之间的a可能以什么方式不同? (不幸的是,最初设置a的python代码非常非常长...我不想让每个人都厌烦1000多个行)

How is it possible that a formats differently in the two cases? In what ways can a possibly differ between the two scripts, if I've already checked that their value is the same at 17.23105 ? (unfortunately the python code that originally sets a is very, very long... I wouldn't want to bore everyone with 1000+ lines)

推荐答案

浮点数的str表示形式在Python 2上被截断为12位数字.这很不幸.您必须print repr(a)以确保看到足够的精度来唯一标识浮点数.可能只有微小的差异,只有12位数字才能显示出来.

The str representation of a float truncates to 12 digits on Python 2. This is unfortunate. You have to print repr(a) to make sure you see enough precision to uniquely identify the float. There's probably a tiny difference that only shows up after 12 digits.

在Python 3上,strrepr会为浮点数生成相同的输出,因此不会出现此问题.

On Python 3, str and repr produce the same output for floats, so you wouldn't have this problem.

这篇关于python float格式怪异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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