我想在程序中调用一个函数,该函数的格式与下面的相同,但其中的shape值采用x = (426, 240)数组的形式。有人能帮上忙吗?
该函数为:
def f(x):
if x < 0:
return -2*x
else :
return -x
x = np.arange(-100, 100, 1)
plt.plot(x, list(map(f, x)), 'b-') # for python3
#plt.show()

调用函数的代码部分将如下所示:
def nucleation_and_motion_in_G_gradient_fluid_2D(writer, args, R=60):
dx = 2*R / args.height
x = (np.arange(args.width) - args.width // 2) * dx
y = (np.arange(args.height) - args.height // 2) * dx
x, y = np.meshgrid(x, y, indexing='ij')
def source_G(t):
center = np.exp(-0.5*(t-5)**2) * 10
gradient = (1+np.tanh(t-30)) * 0.0003
piecewise_1 = f(x) # ***function f(x) called here***
return -(
np.exp(-0.5*(x*x + y*y)) #+ np.exp(-0.5*((x)**2 + y*y))
) * center + piecewise_1 * gradient # piecewise function test主代码here。
我已经知道该代码适用于结合使用x数组的trapezoid函数,如下所示:
(代码需要:from scipy import signal)
def trapezoid_signal(x, width=2., slope=1., amp=10., offs=1):
a = slope * width * signal.sawtooth(2 * np.pi * 1/10 * x/width - 0.8, width=0.5)/4.
a[a>amp/2.] = amp/2.
a[a<-amp/2.] = -amp/2.
return a + amp/2. + offs
def source_G(t):
center = np.exp(-0.5*(t-5)**2) * 10
gradient = (1+np.tanh(t-30)) * 0.0003
trapezoid = trapezoid_signal(x, width=40, slope=5, amp=50)
return -(
np.exp(-0.5*(x**2 + y**2))
) * center + trapezoid * gradient # one soliton particle in 2 dimensions of xy with z axis as concentration potential发布于 2021-02-06 08:04:55
如果你想做这个
def f(x):
if x < 0:
return -2*x
else :
return -x与矢量化兼容,您可以使用以下(非常常见的)技巧:
def f(x):
neg = x < 0
return neg * (-2 * x) + (1 - neg) * -x它起作用了!
>>> f(np.arange(-5, 5))
array([10, 8, 6, 4, 2, 0, -1, -2, -3, -4])https://stackoverflow.com/questions/66069127
复制相似问题