python array函数_f2py,返回数组的Python函数(向量值函数)

在下面的

Python中,我有五个函数包含在func返回的数组中,我必须集成它.代码调用使用f2py生成的外部Fortran模块:

import numpy as np

from numpy import cos, sin , exp

from trapzdv import trapzdv

def func(x):

return np.array([x**2, x**3, cos(x), sin(x), exp(x)])

if __name__ == '__main__':

xs = np.linspace(0.,20.,100)

ans = trapzdv(func,xs,5)

print 'from Fortran:', ans

print 'exact:', np.array([20**3/3., 20**4/4., sin(20.), -cos(20.), exp(20.)])

Fortran例程是:

subroutine trapzdv(f,xs,nf,nxs,result)

integer :: I

double precision :: x1,x2

integer, intent(in) :: nf, nxs

double precision, dimension(nf) :: fx1,fx2

double precision, intent(in), dimension(nxs) :: xs

double precision, intent(out), dimension(nf) :: result

external :: f

result = 0.0

do I = 2,nxs

x1 = xs(I-1)

x2 = xs(I)

fx1 = f(x1)

fx2 = f(x2)

result = result + (fx1+fx2)*(x2-x1)/2

enddo

return

end

问题是Fortran只在func(x)中集成了第一个函数.

查看打印结果:

from Fortran: [ 2666.80270721 2666.80270721 2666.80270721 2666.80270721 2666.80270721]

exact: [ 2.66666667e+03 4.00000000e+04 9.12945251e-01 -4.08082062e-01 4.85165195e+08]

workarond的一种方法是修改func(x)以返回给定的值

在函数数组中的位置:

def func(x,i):

return np.array([x**2, x**3, cos(x), sin(x), exp(x)])[i-1]

然后更改Fortran例程以使用两个参数调用该函数:

subroutine trapzdv(f,xs,nf,nxs,result)

integer :: I

double precision :: x1,x2,fx1,fx2

integer, intent(in) :: nf, nxs

double precision, intent(in), dimension(nxs) :: xs

double precision, intent(out), dimension(nf) :: result

external :: f

result = 0.0

do I = 2,nxs

x1 = xs(I-1)

x2 = xs(I)

do J = 1,nf

fx1 = f(x1,J)

fx2 = f(x2,J)

result(J) = result(J) + (fx1+fx2)*(x2-x1)/2

enddo

enddo

return

end

哪个有效:

from Fortran: [ 2.66680271e+03 4.00040812e+04 9.09838195e-01 5.89903440e-01 4.86814128e+08]

exact: [ 2.66666667e+03 4.00000000e+04 9.12945251e-01 -4.08082062e-01 4.85165195e+08]

但是这里func的调用次数是必要的5倍(在实际情况下是func

具有300多个功能,因此它将被称为300倍以上.

>有没有人知道一个更好的解决方案,使Fortran识别func(x)返回的所有数组?换句话说,使Fortran将fx1 = f(x1)构建为一个数组,其中5个元素对应于func(x)中的函数.

OBS:我正在使用f2py编译-c –compiler = mingw32 -m trapzdv trapzdv.f90

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值