2

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

даршан
  • 65
  • 10

2 Answers2

1

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

xjcl
  • 5,491
  • 3
  • 32
  • 42
0

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.

Kahn
  • 186
  • 7
  • Thanks for your help, but it doesn't change anything... Do you have another advice/ idea where the problem is caused? – AufsMaulwurf Nov 28 '20 at 15:38
  • The problem occurs at the `würfe[1:x]`, because x is an array not a number (scalar). Try using each member of x individually: `[würfe[:x_] for x_ in x]` – xjcl Nov 28 '20 at 16:54