5

I made a simple code on python interpreter and run it.

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. I think.... it is caused by IEEE 754 rule. 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". IEEE 754 rule does not affect the result.

what is the difference between file based running and interpreter based running?

1
  • 1
    have you tried print(np.sum(w*x)+b) from your interpreter? printing isn't the same as asking the interpreter to represent it Commented Sep 9, 2017 at 8:02

2 Answers 2

8

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__.

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.

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

Sign up to request clarification or add additional context in comments.

3 Comments

I didn't know this before. Awesome explanation!
can you explain how IEEE754 rule didn't work in print()?
@LaserCho -- I'm not sure what you mean -- the decision to implement numpy64.float's __repr__ and __str__ differently is numpy's, really (Python used to do this for floats but has since unified them).
0

I think the difference lies in the fact that you use print() for your file based code, which converts the number, while in the interpreter's case, you don't use print(), but rather ask the interpreter to show the result.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.