用Numpy和Pyp进行条件绘图

2024-04-19 08:15:32 发布

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

我试图绘制一个有条件定义的函数。明确地: U(x)=(2**delta)/((D-D)**delta)*(D/2-(x-x0))**delta,对于小于D/2的abs(x-x0))**delta,否则为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.更少(tempx,tempD)。但是如果我用tempx < tempD替换np.less(tempx, tempD),它仍然不起作用,因为我再次要求一个完整列表的真值。我明白问题不在于numpy,而在于我无法理解如何使用numpy提供的逻辑函数。在

很抱歉,如果这个问题在另一篇帖子中得到了回答,我在这个论坛上搜索,但是除了curve()方法之外,找不到其他东西。但是我想数字阵列在我的实际代码中使用的格式。我敢打赌答案一定很简单,我就是想不起来。在


Tags: 函数代码importnumpyreturnasnpplt
2条回答

抛物线必须是ufunc,所以不能在代码中进行python测试。在

一个简单的解决方法是:

def Parabolic(x, delta, D, AD):
    x0 = np.round(x)
    tempx = np.abs(x-x0)
    tempD = D/2*np.ones(len(x))
    u=(((2**delta)/(D-AD)**delta)*(D/2 - (x-x0))**delta)
    u[tempx>=tempD]=0
    return u  

或者为了避免不必要的计算:

^{pr2}$

第二个稍微快一点:

In [141]: %timeit Parabolic(x,8,.4,.2)
1000 loops, best of 3: 310 µs per loop

In [142]: %timeit Parabolic2(x,8,.4,.2)
1000 loops, best of 3: 218 µs per loop

尝试使用numpy逻辑阵列:

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

def Parabolic(x, delta, D, 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,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))

相关问题 更多 >