KevinShaffer
KevinShaffer

Reputation: 858

Logarithm of an array in Python

from numpy import *
from pylab import plot,show
q=10
time = range(q)
mlist=empty(q)
nlist=empty(q)
m=.9
n=(m+(1e-6))
b=3

for t in range(q):
    mlist[t]=m
    nlist[t]=n
    m=(b*(1-m)*m)
    n=(b*(1-n)*n)

zlist = mlist-nlist
zlist = abs(zlist)
plot(time, log(zlist))
show()

then I want to plot the graph of time,log(zlist)

and everytime I run the program, i get this error. "plot(time,log(zlist)) TypeError: only length-1 arrays can be converted to Python scalars"

Any ideas how to either make zlist not an array so I can take the log, or just what is going wrong in my program? Everything else works well, just that one problem. (just for note, i have imported pylab, numpy, and math)

EDIT: The q value is relatively unimportant, but ideally will eventually be up in the 500-1000 range. and m and n have to be between 0 and 1, and b has to be between 0 and 4.

EDIT X2: It seems to be working now, i'm not sure why but it could either be a)importing log from math as well, or b, the negative value problem, but regardless, it's working well. Thank you to everyone who contributed!

Upvotes: 0

Views: 12885

Answers (2)

Andrew Jaffe
Andrew Jaffe

Reputation: 27087

I suspect that you did from math import * after from numpy import * which means that log is really math.log which won't work on an array.

You should really not use import * in scripts. Instead, you should do

import numpy as np
import matplotlib.pyplot as plt

q=10
time = np.arange(q)
mlist = np.empty(q)
nlist = np.empty(q)
m=.9
n=(m+(10e-6))
b=3

for t in range(q):
  mlist[t]=m
  nlist[t]=n
  m *=b*(1-m)
  n *=b*(1-n)

zlist = mlist-nlist

plt.plot(time, np.log(zlist))

or, better

plt.semilogy(time, zlist)

Upvotes: 6

David Robinson
David Robinson

Reputation: 78610

Try

plot(time, map(log, zlist))

That will apply the log function to each number in zlist.

Upvotes: 0

Related Questions