1

When my friend runs the following code, it gives a RuntimeWarning and returns "inf". However, if I run this same code, it executes without a warning and returns a value.

import numpy as np
total = 0
k = 10**6
arr = np.arange(k, 0, -1)
for i in arr:
    total += 1/(i**2)
print(total)

This is her output:

\Anaconda3\lib\site-packages\ipykernel_launcher.py:7: RuntimeWarning: divide by zero encountered in long_scalars
  import sys
inf

Replacing np.arange() with the built-in range() solves the problem, and she gets the same output as me.

My question is: what is causing this inconsistency between her output and mine? Additionally, why is she seeing a difference when using np.arange vs range, while for me the output is the same?

We are both using python 3.7.4 via Anaconda, and numpy 1.16.5, on 64-bit Windows 10.

5
  • first use print() to see values for arange() and range(). Commented May 27, 2020 at 14:38
  • same issue W10 x64 Python 3.7 Commented May 27, 2020 at 14:39
  • it works correctly for both on LInux Mint (64-bit), Python 3.7.7 (64-bit) numpy 1.18.4, (without Anaconda). The same Python 2.7.17 (64-bit), numpy 1.16.6 Do you use 64-bit Python on both computers? Commented May 27, 2020 at 14:41
  • @furas Just checked. We're both using 64-bit Python. Commented May 27, 2020 at 14:53
  • @furas printing appears to show the same values for both arange() and range(), just with arange() as a numpy array of course. Commented May 27, 2020 at 14:54

1 Answer 1

2

Its to do with what data type Numpy infers when you create arr. For me Numpy infered that I wanted np.int32 & that is just not big enough to hold (10**6)**2 so you end up with an inf value.

If you explcitly declare the data type as say np.float64 the problem resolves itself.

arr = np.arange(k, 0, -1, dtype=np.float64)
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, that does explain the issue on her end. But I don't understand why I am not seeing the same behavior. With the same version of numpy, why would numpy apparently infer different data types between my friend and I?
@L.N.M what value are you getting?
1.6449330668487263 @DrBwts
I must admit that's very odd. For W10 x64 machines the default should be int32 ie a c long int as opposed to a c long long int which your machine seems to be using.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.