Fortran 语言中的无穷大
在 Fortran 中将变量设置为 +Infinity 最安全的方法是什么?目前我正在使用:
program test
implicit none
print *,infinity()
contains
real function infinity()
implicit none
real :: x
x = huge(1.)
infinity = x + x
end function infinity
end program test
但我想知道是否有更好的方法?
What is the safest way to set a variable to +Infinity in Fortran? At the moment I am using:
program test
implicit none
print *,infinity()
contains
real function infinity()
implicit none
real :: x
x = huge(1.)
infinity = x + x
end function infinity
end program test
but I am wondering if there is a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您的编译器支持 ISO TR 15580 IEEE 算术,它是所谓的一部分Fortran 2003 标准比您可以使用来自 ieee_* 模块的程序。
If your compiler supports ISO TR 15580 IEEE Arithmetic which is a part of so-called Fortran 2003 standard than you can use procedures from ieee_* modules.
我不会依赖编译器来支持 IEEE 标准,并且会做与您所做的几乎相同的事情,但有两个更改:
我不会添加
huge(1.)+huge(1.)
,因为在某些编译器上你可能会得到-huge(1.)+1
--- 这可能会导致内存泄漏(不知道原因,但这是一个实验事实,所以说)。您在这里使用的是
real
类型。我个人更喜欢将所有浮点数保留为real*8
,因此所有浮点常量都用d0
限定,如下所示:huge(1.d0 )
。当然,这不是规则;而是规则。有些人更喜欢同时使用real
-s 和real*8
-s。I would not rely on the compiler to support the IEEE standard and do pretty much what you did, with two changes:
I would not add
huge(1.)+huge(1.)
, since on some compilers you may end up with-huge(1.)+1
--- and this may cause a memory leak (don't know the reason, but it is an experimental fact, so to say).You are using
real
types here. I personally prefer to keep all my floating-point numbers asreal*8
, hence all float constants are qualified withd0
, like this:huge(1.d0)
. This is not a rule, of course; some people prefer using bothreal
-s andreal*8
-s.我不确定下面的解决方案是否适用于所有编译器,但这是一种很好的数学方法,可以达到 -log(0) 的无穷大。
对于复杂变量也很有效。
I'm not sure if the solution bellow works on all compilers, but it's a nice mathematical way of reaching infinity as -log(0).
Also works nicely for complex variables.
我不知道什么是最安全的,但我可以为您提供另一种方法。我学会了这样做:
如果您在表达式中使用异常值(我认为这通常是不可取的),您应该仔细注意编译器如何处理它们,否则您可能会得到一些意想不到的结果。
I don't know about safest, but I can offer you an alternative method. I learned to do it this way:
If you are using exceptional values in expressions (I don't think this is generally advisable) you should pay careful attention to how your compiler handles them, you might get some unexpected results otherwise.
对于任何来到此线程的人,可以通过以下方式轻松完成定义 inf/-inf 的十六进制转换:
For anyone coming to this thread, the hexadecimal conversion to define inf/-inf can be easily done by:
这似乎对我有用。
定义一个参数
然后在 if 测试中使用它。
当用 ifort & 编译时跑,我得到
This seems to work for me.
Define a parameter
Then use it in if tests.
When compiled with ifort & run, I get