用Matplotlib绘制Takagi函数

时间:2012-02-24 16:53:06

标签: python matplotlib

我一周前开始使用matplotlib;我试图绘制函数

enter image description here

,其中

enter image description here

我更改了

的代码
from math import*
import numpy as np
import matplotlib.pyplot as plt

def phi(x):
    return min(ceil(x) - x, x - floor(x))

n=50
    def f(x):
        return sum([phi(x*2.0**i)/(2.0**i) for i in range (1,n)])

t = np.arange(0.0, 3.0, 0.1)
plt.plot(t, map(f,t))
plt.show()

但它不起作用。我得到的错误是:

File "C:\Documents and Settings\Macedo\Desktop\exem.py", line 15, in <module>
    plt.plot(t, map(f,t))
  File "C:\Python32\lib\site-packages\matplotlib\pyplot.py", line 2459, in plot
    ret = ax.plot(*args, **kwargs)
  File "C:\Python32\lib\site-packages\matplotlib\axes.py", line 3850, in plot
    for line in self._get_lines(*args, **kwargs):
  File "C:\Python32\lib\site-packages\matplotlib\axes.py", line 325, in _grab_next_args
    for seg in self._plot_args(remaining, kwargs):
  File "C:\Python32\lib\site-packages\matplotlib\axes.py", line 302, in _plot_args
    x, y = self._xy_from_xy(x, y)
  File "C:\Python32\lib\site-packages\matplotlib\axes.py", line 242, in _xy_from_xy
    raise ValueError("x and y must have same first dimension")
ValueError: x and y must have same first dimension

1 个答案:

答案 0 :(得分:7)

问题是如何定义变量。例如,您写道:

def phi(x):
    phi = lambda x: min(ceil(x) - x, x - floor(x))

您可以将其定义为

def phi(x):
    return min(ceil(x) - x, x - floor(x))

phi = lambda x: min(ceil(x) - x, x - floor(x))

在Python中查找函数定义和lambda函数。

f的定义不应该循环。所以你需要像

这样的东西
n=50
def f(x):
    return sum([phi(x*2.0**i)/(2.0**i) for i in range (1,n)])

要摆脱“只有长度为1的数组可以转换为Python标量”的错误,请使用

plt.plot(t, map(f,t))

而不是

plt.plot(t, f(t))

问题是math.ceil需要一个标量,而不是在数组上按元素运算,这就是你想要的。因此,map现在将在f上以t元素运行。

最后,我使用的代码是:

from math import *
import numpy as np
import matplotlib.pyplot as plt

def phi(x):
    return min(ceil(x) - x, x - floor(x))

n=50
def f(x):
    return sum([phi(x*2.0**i)/(2.0**i) for i in range (1,n)])

t = np.arange(0.0, 3.0, 0.1)
plt.plot(t, map(f,t))
plt.show()

输出

enter image description here

这是在Python 2.7.2中。正如@ThomasK所建议的那样,对于Python 3,您可能需要list(map(f,t))