问题描述
我对Fortran很新,而且我正在玩功能。
我在一个非常简单的程序中发现了一个非常奇怪的行为,我无法以任何方式证明它的合理性。这里是简单的代码:
$ pre $ code $ Real $ 8函数gamma(v)
隐含无
实数* 8 :: v
gamma = 1.0_8 / Sqrt(1.0_8 - v ** 2)
结束函数gamma
程序test_gamma
隐含无
Real * 8 :: v = 0.5_8,gamma
print *,Gamma =,1.0_8 / Sqrt(1.0_8 - v ** 2)
结束程序
这会显示确切的结果: 1.1547005383792517
但如果我使用函数调用,做相同的计算, print *,Gamma =,gamma(v)
我有意想不到的结果 1.7724538509055161
。
我在这里错过了什么?
值1.7724538509055161对应于参数为0.5的(数学)伽马函数的(正确)结果。标准内部函数 gamma
返回与此gamma函数相对应的结果。 在调用 gamma
你已经声明gamma返回一个 real * 8
结果,但是你没有给出 external
属性,或者通过其他方式创建一个接口。所以,内在的东西就是调用:当编译主程序时,编译器知道没有其他选择[我希望编译器会在这种情况下警告你,如果你问的话。]
我建议你调用你的函数而不是 gamma
,而不是添加 external
属性。我甚至建议对于有程序中可用接口的函数。
通过可用接口,我的意思是你可以:
- 将您的
gamma
函数内部放入主程序中; - 通过主程序将
gamma
函数放入模块use
d中; - [提供接口块。]
有关详细信息,请参阅您的编程指南。 b
$ b
最后,我还建议另外一件事:没有 real * 8
。你可以在这里阅读很多有关这方面的评论。
I am quite new to Fortran and I was 'playing' with functions.I found a quite weird behavior in a very simple program that I cannot justify in any way. Here is the simple code:
Real*8 Function gamma(v)
Implicit None
Real*8 :: v
gamma = 1.0_8 / Sqrt(1.0_8 - v ** 2)
End Function gamma
Program test_gamma
Implicit None
Real*8 :: v = 0.5_8, gamma
print *,"Gamma = ", 1.0_8 / Sqrt(1.0_8 - v ** 2)
End Program
This prints the exact result: 1.1547005383792517
but if I use the function call, doing the same calculation, print *,"Gamma = ", gamma(v)
I have the unexpected result 1.7724538509055161
.
What am I missing here?
The value 1.7724538509055161 corresponds to the (correct) result from the (mathematical) gamma function with argument 0.5. The standard intrinsic function gamma
returns result corresponding to this gamma function.
In your program calling gamma
you have declared gamma to return a real*8
result, but you haven't given it the external
attribute, or made an interface available through other means. So, the intrinsic is to called instead: when compiling the main program the compiler "knows" about no alternative [I'd expect a compiler warning in such circumstances if you ask for it.]
I'd recommend that you call your function something other than gamma
rather than add the external
attribute. I'd even recommend that for a function which has an interface available in the program.
By "interface available", I mean you could:
- put your
gamma
function internal to the main program; - put your
gamma
function in a moduleuse
d by the main program; - [offer an interface block.]
Consult your programming guide for details.
Finally, I'd also recommend one other thing: no real*8
. You can read many comments here on SO about that.
这篇关于奇怪的函数调用行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!