gfortran如何处理整数与实数的幂运算?我一直以为是相同的,但请考虑示例:
How does gfortran handle exponentiation with a integer vs a real? I always assumed it was the same, but consider the example:
program main implicit none integer, parameter :: dp = selected_real_kind(33,4931) real(kind=dp) :: x = 82.4754500815524510_dp print *, x print *, x**4 print *, x**4.0_dp end program main使用gfortran进行编译会得到
Compiling with gfortran gives
82.4754500815524510000000000000000003 46269923.0191143410452125643548442147 46269923.0191143410452125643548442211现在显然这些数字几乎是一致的-但是如果gfortran以相同的方式处理整数和实数以求幂,我希望它们是相同的.有什么作用?
Now clearly these numbers almost agree - but if gfortran handles integers and reals for exponentiation in the same way I would expect them to be identical. What gives?
推荐答案略微扩展程序将显示正在发生的事情:
Expanding your program slightly shows what is going on:
ijb@ianbushdesktop ~/work/stack $ cat exp.f90 program main implicit none integer, parameter :: dp = selected_real_kind(33,4931) real(kind=dp) :: x = 82.4754500815524510_dp print *, x print *, x**4 print *,(x*x)*(x*x) print *,Nearest((x*x)*(x*x),+1.0_dp) print *, x**4.0_dp end program main编译和运行可以得到:
ijb@ianbushdesktop ~/work/stack $ gfortran --version GNU Fortran (GCC) 7.4.0 Copyright (C) 2017 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ijb@ianbushdesktop ~/work/stack $ gfortran exp.f90 ijb@ianbushdesktop ~/work/stack $ ./a.out 82.4754500815524510000000000000000003 46269923.0191143410452125643548442147 46269923.0191143410452125643548442147 46269923.0191143410452125643548442211 46269923.0191143410452125643548442211 ijb@ianbushdesktop ~/work/stack $因此
看起来编译器很聪明,可以算出可以通过乘法来完成整数幂运算,这比一般的幂运算要快得多
It looks like the compiler is clever enough to work out that integer powers can be done by multiplies, which is much quicker than a general exponentiation function
使用通用幂函数与乘法答案仅相差1位.鉴于我们不能说本身更准确,因此我们必须接受两者都一样准确
Using the general exponentiation function is only 1 bit different from the multiplication answer. Given we can't say per se which is more accurate we must accepts both as equally accurate
因此,总而言之,编译器会在可能的情况下使用简单的乘法运算,而不是使用完整的幂运算程序,但是即使必须使用更昂贵的路由,编译器也会给出相同的答案,以供仔细考虑相同"一词的含义.
Thus in conclusion the compiler uses simple multiplies where possible instead of a full blown exponentiation routine, but even if it has to use the more expensive route it gives the same answer, for carefully considered meaning of the word "same"