简体   繁体   English

相当于python numpy.minimum的Fortran

[英]Fortran equivalent of python numpy.minimum

I am trying to re-write some python code in fortran, specifically the line 我正在尝试在fortran中重新编写一些python代码,特别是该行

separation[a, :] = sum(np.minimum(1 - distances, distances) ** 2)

The important part being the use of np.minimum to take the element-wise minimum of two multi-dimensional arrays. 重要的部分是使用np.minimum取两个多维数组的元素方式最小值。 Distances is a (3, N) array of N coordinates (x,y,z). 距离是N个坐标(x,y,z)的(3,N)数组。 I can't find a similar function in fortran, so I wrote my own using: 我在fortran中找不到类似的函数,因此我使用以下代码编写了自己的函数:

  do b = 1, N
    temp = 0.0
    do c = 1, 3
      if ((1 - distances(c, b)) .LE. distances(c, b)) then
        temp = temp + (1 - distances(c, b)) ** 2
      else
        temp = temp + (distances(c, b)) ** 2
      end if
    end do
    separation(a, b) = temp
  end do

Unsurprisingly this code is very slow, I am not very experienced in fortran yet so any recommendations as to improving this code or suggesting an alternative method would be greatly appreciated. 毫不奇怪,这段代码非常慢,我在fortran方面还不是很有经验,因此,对改进此代码或建议使用其他方法的任何建议将不胜感激。

I thought perhaps a where statement might help, as the following code in python works 我认为也许where语句可能会有所帮助,因为python中的以下代码有效

separation[a, :] = sum(np.where(1 - distances <= distances, (1 - distances), distances) ** 2)

But while fortran has where statements, they seem to work rather differently to python ones and they don't seem to be much use here. 但是,尽管fortran具有where语句,但它们的工作方式似乎与python的工作方式完全不同,并且在这里似乎用处不大。

it is nearly the same. 它几乎是相同的。 Most fortran intrinsics operate component-wise on arrays ( assuming you have at least fortran95 ) 大多数fortran内部函数在数组上以组件方式操作(假设您至少具有fortran95)

 real a(2,4),b(4)
 a=reshape([.1,.2,.3,.4,.5,.6,.7,.8],shape(a)) 
 b=sum(min(1-a,a)**2,1)
 write(*,'(4f5.2)')b
 end

0.05 0.25 0.41 0.13 0.05 0.25 0.41 0.13

note fortran's sum would by default sum the whole array. 请注意,默认情况下,fortran的sum将对整个数组求和。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM