python中的浮点给出了错误的答案 [英] floating point in python gives a wrong answer

查看:34
本文介绍了python中的浮点给出了错误的答案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我计算了以下内容:

<预><代码>>>>浮动(10.0-9.2)0.800000000000000*7*

即使做 10.0-9.2 也给出了上述结果.为什么结果中出现了额外的 7?

我使用的是 Python 3.2.

解决方案

浮点运算存在一些内在问题,因为它基于数字的二进制近似.

Python 文档中有对此的很好解释.

如果您需要更准确的答案,可以查看decimal 模块.

I calculated the following:

>>> float(10.0-9.2)
0.800000000000000*7*

even doing 10.0-9.2 gave the above result. Why is the extra 7 coming in the result?

I'm on python 3.2.

解决方案

Floating point arithmetic has built-in problems as it's based on a binary approximation of numbers.

There is a good explanation of this in the Python docs.

You can check out the decimal module if you need more exact answers.

这篇关于python中的浮点给出了错误的答案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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