Question about the np.dot and for loop

Hi,

I wonder why there is a difference between the calculation result of using np.dot() and for loop.

@Michael1 Many packages in Python (including Numpy) are pre-compiled optimized code for various hardware platforms. When using a traditional for loop, the python interpreter needs to interpret the code and generate binary at runtime which reduces the performance.

It is always desirable to use in-built packages and functions whenever they are available in real-world scenarios

Reference - What is NumPy? — NumPy v1.20 Manual

2 Likes

That makes sense, but why there is a difference in the result? Should the result be the same?

@Michael1 The reason for variation in output can be attributed to how floating-point numbers are represented internally in a computing device and the actual implementation of numpy.dot() which is more sophisticated than doing multiplication using plain loops.

Reference -

https://www.log2base2.com/storage/how-float-values-are-stored-in-memory.html

2 Likes

Thanks for your clarification. Could I know which one should be the correct one based on the mathmatics? Also, would this difference make huge error in the in real-world scenarios?