在 fortran 中定义长参数向量的巧妙方法 [英] Neat way to define a long parameter vector in fortran

查看:24
本文介绍了在 fortran 中定义长参数向量的巧妙方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我现在遇到了这个问题.我有一组(大量)参数,我想将它们组织成一个向量.

Well, I've this problem now. I've a (huge) set of parameters I'd like to organize in a vector.

当然,我可以这样做:

real, dimension(64)          :: CONST

CONST(1) = 2.4
CONST(2) = 1.4
...
CONST(n) = CONST(1)*CONST(14)**CONST(7)
...
CONST(64) = ABS(CONST(18))

(请注意,有些常量与其他常量相关).

(Note that some of the constants are related to other constants).

但在这种情况下,我不会在变量中拥有 parameter 属性,而我希望拥有.

But in that case, I wouldn't have the parameter attribute in the variable, wich I'd like to have.

我可以考虑的另一个选项是使用属性parameter,在这种情况下,我必须在变量定义期间将值分配给向量.比如:

The other option I can think about is using the attribute parameter, in which case I've to assign the value to the vector during the definition of the variable. Something like:

real, parameter, dimension(64) :: CONST =[2.4 , 1.4       , &
                                                ...       , &
                                                1.5412356 , &
                                                ...       , &
                                                342.5]

但是,有一些巨大的对应物:

But, with some huge counterparts:

  • 由于变量定义过程中的行数过多,代码变得难以阅读.
  • 我无法将常量定义为其他常量的函数.

所以,

  • 有一种巧妙的方法(如在第一个代码中)在 Fortran 中使用属性 parameter 定义长向量?
  • (我想它不是)一旦我定义了变量的值,有没有办法改变它的属性?

感谢您的宝贵时间.

推荐答案

参数的问题只是不能定义常量数组依赖自身.但是您可以定义基本量,然后定义包括派生量在内的整个数组,如下所示:

The problem with the parameter is only that you can't define the constant array to depend on itself. But you could define the fundamental quantities, and then the whole array including the derived quantities, as so:

program foo
implicit none

real, dimension(2), parameter :: basic = [2.4, 1.4]
real, dimension(4), parameter :: all = [basic(1), basic(2),           &   
                                        basic(1)*basic(2)**basic(1),  &
                                        abs(basic(1))]

print *, basic
print *, all

end program foo

事实上,如果你想这样做,你不妨命名基本量:

and in fact if you want to go that way, you might as well name the fundamental quantities:

program foo
implicit none

real, parameter :: height = 2.4, bodymass = 1.4
real, dimension(4), parameter :: all = [height, bodymass,     &   
                                        height*bodymass**2,  &
                                        abs(height)]

print *, height, bodymass
print *, all

end program foo

我无法想象身高是你需要取绝对值的那种东西,但你明白我的意思.

I can't imagine height is the sort of thing you need to take the absolute value of, but you see my point.

这篇关于在 fortran 中定义长参数向量的巧妙方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆