How to plot 500 pairs of successive random numbers in python?
I am new to python and one of the problems I am working on is to plot 500 pairs of successive random numbers. I have a formula that generates the numbers seen below:
x-axis
>>> a=128
>>> c=0
>>> m=509
>>> n=500
>>> seed = 10
>>> for i in range (1,n):
new_seed=(a*seed+c)%m
seed = new_seed
print new_seed
y-axis
>>> a=269
>>> c=0
>>> m=2048
>>> n=500
>>> seed = 10
>>> for i in range (1,n):
new_seed=(a*seed+c)%m
seed = new_seed
print new_seed
What I am wondering now is how I can turn these results into an array or list. I have attempted to put plt.plot(new_seed) in the loop statement but that did not work when I tried to plot. Any ideas?
I used import matplotlib.pyplot as plt
Thanks in advance for the help!!
你可能应该做一些(更多)python教程。列表是Python的一个基本方面,它似乎你不了解它们...
import matplotlib.pyplot as plt
import random
x = []
a,seed,c,m,n = 128,10,0,509,500
for i in range (1,n):
new_seed=(a*seed+c)%m
seed = new_seed
x.append( new_seed)
a,seed,c,m,n = 269,10,0,2048,500
y= []
for i in range (1,n):
new_seed=(a*seed+c)%m
seed = new_seed
y.append( new_seed)
plt.plot(x,y)
plt.show()
You're printing the numbers ( print new_seed
), which is not going to be of any use if you're trying to plot them. Does that make sense?
What you should do instead is save each number to the next available position in a list as you generate it. A simple way to do this would be to create an empty list before the loop, and each time you generate a number, just append
it to the list instead of printing it.
xlist = []
for i in xrange(n):
new_seed = # generate the number
xlist.append(new_seed)
and similarly for ylist
.
In practice, what you would do is use a list comprehension, like this:
xlist = [generate_number(...) for i in xrange(n)]
which is just a shorthand syntax for exactly what I wrote above. (Well, it also runs faster) It does require you to encapsulate the process of generating a random number in a function, but that's a good idea anyway.
Then you can use matplotlib to plot xlist
vs. ylist
.
上一篇: PHP和导入pylab