Python数学错误? [英] Wrong math with Python?

查看:82
本文介绍了Python数学错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是从Python开始,所以这可能是我的错误,但是...

Just starting out with Python, so this is probably my mistake, but...

我正在尝试Python.我喜欢将其用作计算器,并且正在逐步研究一些教程.

I'm trying out Python. I like to use it as a calculator, and I'm slowly working through some tutorials.

我今天遇到了奇怪的事情.我想找出2013 * 2013,但是我写错了东西,写了2013 * 013,得到的是:

I ran into something weird today. I wanted to find out 2013*2013, but I wrote the wrong thing and wrote 2013*013, and got this:

>>> 2013*013
22143

我检查了计算器,然后得出22143错误的答案! 2013 * 13应该是26169.

I checked with my calculator, and 22143 is the wrong answer! 2013 * 13 is supposed to be 26169.

为什么Python给我一个错误的答案?我的旧卡西欧计算器无法执行此操作...

Why is Python giving me a wrong answer? My old Casio calculator doesn't do this...

推荐答案

由于八进制算术,013实际上是整数11.

Because of octal arithmetic, 013 is actually the integer 11.

>>> 013
11

以前导零表示,013解释为以8为底的数字,并且1 * 8 1 + 3 * 8 0 =11.

With a leading zero, 013 is interpreted as a base-8 number and 1*81 + 3*80 = 11.

注意:此行为是在python 3中进行了更改.这是 PEP 3127

Note: this behaviour was changed in python 3. Here is a particularly appropriate quote from PEP 3127

整数的默认八进制表示形式使 不熟悉C语言的人.这非常容易 无意中创建了一个带有错误值的整数对象,因为 对于Python语言,"013"表示十进制11",而不是十进制13" 本身,这不是大多数人会赋予它的意思 文字.

The default octal representation of integers is silently confusing to people unfamiliar with C-like languages. It is extremely easy to inadvertently create an integer object with the wrong value, because '013' means 'decimal 11', not 'decimal 13', to the Python language itself, which is not the meaning that most humans would assign to this literal.

这篇关于Python数学错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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