TypeError:尝试打印函数时,只有size1数组才能转换为Python标量

2024-04-29 06:55:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到了当前代码:

from math import cos, sin, pi
import numpy as np
import matplotlib.pyplot as plt

def f(x):
    
    values = []
    s = 0
    for n in range(1, 6, 1):
        s += -((2/(n*pi))*(((cos((n*pi)/2))-1)*(sin((n/2)*x))))
        values.append(s)
        
    return values

x = np.linspace(-2*pi, 6*pi, 500)
plt.plot(f(x))

我应该绘制f(x),但当我运行代码时,我得到以下错误:

TypeError: only size-1 arrays can be converted to Python scalars

你知道我做错了什么吗

任何帮助都将不胜感激


Tags: 代码fromimportnumpymatplotlibdefasnp
2条回答

如果您是编程新手,这可能与您现在所做的有点不同,但是我基本上将函数拆分,以解释每个组件的功能,更重要的是,使用了numpy的内置函数,它将被证明比嵌套循环更有效,尤其是当您的数据变得更大时

为了理解函数f发生了什么,请在Python中查找(列表)理解,但它基本上是一个用单行表示的for循环

In [24]: import numpy as np
    ...: import matplotlib.pyplot as plt

In [25]: def summand(n, x):
    ...:     """ Return an array of `x`'s size for a given value of `n`.
    ...:     Each element of the array is a value of the function computed
    ...:     at a value in `x` with the given `n`.
    ...:     """
    ...:     return (2 / (n * np.pi)) * (np.cos(n * np.pi / 2) - 1) * np.sin(n * x / 2)
    ...:

In [26]: def f(x, N=5):
    ...:     """ Return the sum of the summands computed for
    ...:     values of `n` ranging from 1 to N+1 with a given array `x`
    ...:     """
    ...:     return sum(summand(n, x) for n in range(1, N+1))
    ...:

In [27]: x = np.linspace(-2*np.pi, 6*np.pi, 500)

In [28]: plt.plot(x, f(x))
Out[28]: [<matplotlib.lines.Line2D at 0x23e60b52a00>]

In [29]: plt.show()

enter image description here

我认为公式中的x值只适用于x的一个值,并且由于列表中有多个x,因此必须迭代每个for xval in x:,执行计算并将计算出的值附加到values列表中

from math import cos, sin, pi
import numpy as np
import matplotlib.pyplot as plt

def f(x):
    values = []
    for xval in x:
        s = 0
        for n in range(1, 6, 1):
            s += -((2/(n*pi))*(((cos((n*pi)/2))-1)*(sin((n/2)*xval))))
        values.append(s * -1)
        
    return values

x = np.linspace(-2*pi, 6*pi, 500)
plt.plot(f(x))
plt.show()

相关问题 更多 >