简体   繁体   English

为什么运行python解释器和python代码之间的结果不同?

[英]why the result is different between running python interpreter and python code?

I made a simple code on python interpreter and run it. 我在python解释器上创建了一个简单的代码并运行它。

Python 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 16:02:32) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> x=np.array([0,1])
>>> w=np.array([0.5,0.5])
>>> b=-0.7
>>> np.sum(w*x)+b
-0.19999999999999996

the result -0.19999999999999996 is weird. 结果-0.19999999999999996很奇怪。 I think.... it is caused by IEEE 754 rule. 我认为......它是由IEEE 754规则引起的。 But when I try to run almost same code by file, result is a lot different. 但是当我尝试按文件运行几乎相同的代码时,结果会有很大不同。

import numpy as np
x = np.array([0,1])
w = np.array([0.5,0.5])
b = -0.7
print(np.sum(w * x) + b)

the result is "-0.2". 结果是“-0.2”。 IEEE 754 rule does not affect the result. IEEE 754规则不会影响结果。

what is the difference between file based running and interpreter based running? 基于文件的运行和基于解释器的运行有什么区别?

The difference is due to how the interpreter displays output. 差异是由于解释器如何显示输出。

The print function will try to use an object's __str__ method, but the interpreter will use an object's __repr__ . print函数将尝试使用对象的__str__方法,但解释器将使用对象的__repr__

If, in the interpreter you wrote: 如果你在翻译中写道:

...
z = np.sum(w*x)+b
print(z)

(which is what you're doing in your code) you'd see -0.2 . (这是你在代码中所做的)你会看到-0.2

Similarly, if in your code you wrote: 同样,如果在您的代码中,您写道:

print(repr(np.sum(w * x) + b))

(which is what you're doing in the interpreter) you'd see -0.19999999999999996 (这是你在翻译中所做的)你会看到-0.19999999999999996

我认为不同之处在于,您使用print()作为基于文件的代码(转换数字),而在解释器的情况下,您不使用print() ,而是要求解释器显示结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM