我们可以在Fortran中创建纯函数来生成随机数吗? [英] Can we create pure functions in Fortran which generate random numbers?

查看:196
本文介绍了我们可以在Fortran中创建纯函数来生成随机数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是使用可以在DO CONCURRENT结构中使用的随机数编写纯函数.编译器似乎不允许这样做.

My goal is to write a pure function using random numbers which can be used in a DO CONCURRENT structure. The compiler does not seem to permit this.

mwe.f95:8:30:

             call init_seed ( )
                              1
Error: Subroutine call to ‘init_seed’ at (1) is not PURE
mwe.f95:9:36:

             call random_number ( y )
                                    1
Error: Subroutine call to intrinsic ‘random_number’ at (1) is not PURE
mwe.f95:16:8:

     use myFunction
        1
Fatal Error: Can't open module file ‘myfunction.mod’ for reading at (1): No such file or directory
compilation terminated.

为什么会这样,并且有一种方法可以在纯例行程序中生成随机数?

Why is this so and is there a way to generate random numbers in a pure routine?

随后是MWE.编译命令为gfortran mwe.f95.编译器版本为GCC 5.1.0.

The MWE follows. Compilation command is gfortran mwe.f95. Compiler version is GCC 5.1.0.

module myFunction

    implicit none

contains
    pure real function action ( ) result ( new_number )
        real :: y
            call init_seed ( )
            call random_number ( y )
            new_number = y**2
    end function
end module myFunction


program mwe
    use myFunction
    implicit none
    real :: x

        x = action ( )

end program mwe

推荐答案

这完全与纯净概念背道而驰.如在真正的函数语言中所见,真正的纯函数应始终为相同的输入返回相同的结果. Fortran纯函数可以读取模块变量,因此更加复杂.

This is completely against the concept of pureness. True pure functions, as found in true functional languages, should always return the same result for the same input. Fortran pure functions can read module variables and therefore are more complex.

拥有任何函数(不仅仅是纯函数)来返回伪随机数甚至不是一个好主意.如果表达式中有更多函数调用,则允许Fortran编译器仅对函数求值一次.当该函数是纯函数时,这更有可能或更合理.

It is not even a good idea to have any function, not just a pure function, to return pseudo-random numbers. When you have more function calls in an expression the Fortran compiler is permitted to evaluate the function just once. That is even more likely, or better justified, when that function is pure.

我建议只使用常规的DO循环并调用random_number或其他自定义PRNG子例程.即使您想要自动并行化或类似的方法,编译器通常也能够将常规DO循环与DO CONCURRENT等同对待.

I would suggest to just use regular DO loops and call random_number or other custom PRNG subroutine. Even if you want automatic parallelization or similar , the compilers are normally capable to treat regular DO loops equally well as DO CONCURRENT.

这篇关于我们可以在Fortran中创建纯函数来生成随机数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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