"only integer scalar arrays can be converted to a scalar index"

Viewed 361

I am generating a numpy array with 1000000 random numbers between 1 and 6 and i would like to calculate the mean of the first 10, 100, 1000, ... I also want to plot the means on logarithmic scale. I mustn't use anything but Python with numpy and matplotlib. Why do i get this error? What have i done wrong?

This is my code:

throws=numpy.random.randint(1,7,(1000000))
print(throws[1:10])

x=np.logspace(1,6,6)
plt.plot(x, int(mean(throws[1:x])))
plt.semilogx()

Sorry for my bad English and the german variable names...

2 Answers

You're almost there! You just have to slice the würfe (dice throws) array and then apply mean to it, this is easiest with

würfe=numpy.random.randint(1,7,(1000000))
print(würfe[1:10])

x=np.logspace(1,6,6)
y=[np.mean(würfe[:int(x_)]) for x_ in x]  # <--- just add this line
plt.plot(x, y)
plt.semilogx()
plt.show()

x here is [10, 100, 1000, 10000, 100000, 1000000] and würfe[:int(x_)] converts x from float to int and uses it to slice the original array into the parts you want to take the mean of. The mean is then taken with a Python list comprehension.

enter image description here

Try Run:

import numpy
x=numpy.logspace(1,6,6)
print(x.dtype)

Shows

float64

So würfe[1:x] is using float64 array as index,certainly it can't be right.

Use

x=numpy.logspace(1,6,6).astype(int)

And also würfe[1:x] requires x to be a int but not an array.

Related