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

查看:20
本文介绍了我们可以在 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 CONCURRENT 一样处理常规 DO 循环.

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天全站免登陆