加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – Numpy和Pyplot的条件绘图

发布时间:2020-12-20 11:50:59 所属栏目:Python 来源:网络整理
导读:我试图绘制一个有条件定义的函数.特别: U(x)=(2 ** delta)/((Dd)** delta)*(D / 2 – (x-x0))** delta,abs(x-x0)小于D / 2和0除此以外. 但我的问题是我希望将x,x0作为numpy数组,因为这是我在其余实际代码中使用它们的方式. 我已经设置了以下示例: import n
我试图绘制一个有条件定义的函数.特别:
U(x)=(2 ** delta)/((Dd)** delta)*(D / 2 – (x-x0))** delta,abs(x-x0)小于D / 2和0除此以外.

但我的问题是我希望将x,x0作为numpy数组,因为这是我在其余实际代码中使用它们的方式.

我已经设置了以下示例:

import numpy as np
import matplotlib.pyplot as plt
AD = 0.2
D = 0.4
delta = 8

def Parabolic(x,delta,D,AD):
    x0 = np.round(x)
    tempx = np.abs(x-x0)
    tempD = D/2*np.ones(len(x))
    if tempx<tempD:
        return ((2**delta)/(D-AD)**delta)*(D/2 - (x-x0))**delta
    else:
        return 0

figure = plt.figure(figsize=(10,8),dpi=72)  
xmin = -1.0
xmax = 1.0
X = np.linspace(xmin,xmax,1000)
plt.plot(X,Parabolic(X,delta=8,D=0.4,AD=0.2))

显然,这个例子不起作用,因为行tempx< tempD引起了列表的真值 - 值不明确的错误. 我搜索了numpy的文档并找到了函数np.less(tempx,tempD).但如果我取代tempx<使用np.less(tempx,tempD)的tempD它仍然不起作用,因为我再一次要求整个列表的真值.我知道问题不是numpy,而是因为我无法理解如何使用numpy提供的逻辑函数. 我很抱歉,如果这在另一篇文章中有所回答,我在这个论坛中搜索但除了curve()方法之外找不到别的东西.但是我想保留我的numpy.array格式以用于我的实际代码.我敢打赌答案必须非常简单,我想不出来.

解决方法

试试这个使用numpy逻辑数组:

import numpy as np
import matplotlib.pyplot as plt
AD = 0.2
D = 0.4
delta = 8

def Parabolic(x,AD):
    rtn_arr = np.zeros(len(x))
    x0 = np.round(x)
    tempx = np.abs(x-x0)
    tempD = D/2*np.ones(len(x))
    lgc_arr = tempx<tempD
    x_cut = x[lgc_arr]
    x0_cut = x0[lgc_arr]
    rtn_arr[lgc_arr] = ((2**delta)/(D-AD)**delta)*(D/2 - (x_cut-x0_cut))**delta
    return rtn_arr

figure = plt.figure(figsize=(10,dpi=72)
xmin = -1.0
xmax = 1.0
X = np.linspace(xmin,AD=0.2))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读