【问题标题】:Simple Python Function with an if statement not working?带有 if 语句的简单 Python 函数不起作用?
【发布时间】:2020-04-15 10:17:18
【问题描述】:

为什么下图定义的函数不起作用?我收到错误消息 ValueError:具有多个元素的数组的真值不明确。使用 a.any() 或 a.all()

提前致谢。

import math
from math import sin, cos, exp, pi, sqrt
from matplotlib import pyplot as plt

def pulse(Amax,td,t):
    if t<=td:
        y = Amax*sin((pi/td)*t)
    else:
        y = 0
    return y

t = np.linspace(0,4*pi,100)
Amax=10
td=11/1000
plt.plot(t,pulse(Amax,td,t), 'r', label='pulse A=10,td=11')

【问题讨论】:

标签: python-3.x function


【解决方案1】:

t &lt;= td 中,您直接将标量与数组进行比较。这种类型的操作是模棱两可的,因为它无法确定真值应该是什么。

【讨论】:

  • 谢谢。那么定义这种简单函数的“标准”python方式是什么?
  • 这实际上来自 numpy,它不是标准的 Python。检查他们的文档。
【解决方案2】:

在 plt.plot 中,您提供 2 个数组。最好在适当的条件下使用迭代数组 t 预先创建数组 y ,否则您的函数脉冲应该返回一个数组。 喜欢

def pulse (Amax,td,t):
    y=[]
    for i in t:
        if i <= td:
            y.append(Amax*sin((pi/td)*i))
        else:
            y.append(0)
    return y

最后只使用 plt.plot(t,pulse(Amax,td,t), whatever you want here)

【讨论】:

    【解决方案3】:

    丑陋但有效

    i=0
    y=zeros(N0); ti=zeros(N0)
    
    for t in np.arange(0,tend,dt):
        ti[i]=t
        if t <= td:
            y[i]=amax*np.sin(wf*t)
        else:
            y[i]=0
        i+=1
    

    ------------

    也许是更好的代码

    trg = np.arange(0,tend,dt)   # start,stop,step
    for i,t in enumerate(trg):
        if t <= td:
            y[i]=amax*np.sin(wf*t)
        else:
            y[i]=0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多