Fortran功能说明

时间:2012-04-16 12:29:48

标签: c# function fortran

我在Fortran中有这个功能,我试图用C#重新编码

C **************************************************************** 
C    FUNCTION   POLY 
C***************************************************************** 
      FUNCTION POLY(N,A,X) 
      DIMENSION A(N) 
C
      POLY    = 0. 
      L       = N 
      DO 1 K  = 1,N 
      POLY    = POLY*X + A(L) 
1     L       = L-1 
      RETURN 
      END 
C***************************************************************** 

我发现DIMENSION A(N)创建了N值的向量,但我们已经从函数参数中获得了变量A,这是否意味着数组值都等于{ {1}}?如果是,那么A的用途是什么。 顺便说一句,任何人都可以解释这个功能是做什么的,所以我可以在C#中重新实现它#

4 个答案:

答案 0 :(得分:5)

      FUNCTION POLY(N,A,X)      ! implicitly real (float) function poly(int n,int a,real x)
      DIMENSION A(N)            ! shape A as 1d array of n values in this scope
C                               ! say nothing (blank comment)
      POLY    = 0.              ! initialise return variable to float value 0
      L       = N               ! set L (implicitly integer) to n
      DO 1 K  = 1,N             ! for(int k=1; k<=n; ++k)
      POLY    = POLY*X + A(L)   !    update return variable
1     L       = L-1             !    decrement L
      RETURN                    ! return current value for poly
      END 

所以用c语法:

float poly(int n, int a, float x) {
    // redim a(n)
    float result = 0;
    int l = n;
    for(int k=1; k <= n; ++k) {
        result = result*x + a(l);
        --l;
    }
    return result;
}

不翻译的位是将A重新定义为数组。在C中,您将传递一个指针并将其用作数组,而在C ++ / C#中,您可能会传递具有自己的length属性的类似矢量的结构。

在C#中,使用列表:

float poly(List<float> coeffs, float x) {
    float result = 0;
    for(int i=coeffs.Count-1; i >= 0; --i) {
        result = result*x + coeff[i];
    }
    return result;
}

答案 1 :(得分:3)

它评估形式为x的多项式:

a[1] + a[2]x + a[3]x^2 + ... a[N]x^(N-1)

请记住,Fortran使用基于1的数组索引,并且我在此等式中遵循该约定。


你可以用C#写这个:

double EvaluatePolynomial(double[] a, double x)
{
    double result = 0.0;
    int i = a.Length;
    while (i>0)
    {
        i--;
        result = result*x + a[i];
    }
    return result;
}

这里我们使用适合C#的基于0的数组索引。因此,此函数按以下形式x重新计算多项式:

a[0] + a[1]x + a[2]x^2 + ... a[N-1]x^(N-1)

答案 2 :(得分:2)

稍微猜测我认为这是指定参数A本身是N元素的数组。

因此,对于C#等价物,您不需要单独的N参数;您只需要将A作为double[]传递,因为.NET数组可以告诉您.Length

该函数使用Horner's method评估多项式。

答案 3 :(得分:2)

DIMENSION A(N)只是声明A伪参数的详细信息(PARAMETERs在Fortran中是非常不同的),即它表示它是从1到N的数组。其他的未声明这样,因为该函数使用隐式类型。