赋值后的真实值与真实表达式不同 [英] Real value after assignment different from the real expression
问题描述
我正在翻译 Fortran 中的代码.我在分配期间出现奇怪的行为.我知道添加代码可能会很有帮助,但我无法添加确切的代码(我没有获得授权)并且我没有成功复制它.
以下几行(qk 是预定义的,qk1 不是):
打印*,"qk",qk打印*,"qk1",qk1QK1=QK打印*,"qk",qk打印*,"qk1",qk1
并且我打印了这些值:
qk 21909779.000000000qk1 6.44842193E+32qk 21909779.000000000qk1 21909780.0
关键是我希望 qk1 等于 qk ......为什么它们不同?当我尝试复制它时,显然我得到了相同的值.
由于我没有添加代码,所以我不希望得到准确的答案...有没有人知道要检查什么?
原因是如注释中指出的那样,qk 是单精度,qk1 双精度,并且在所需的值处单精度实数之间的间距为 2:
>
程序 one_out使用,内在 :: iso_fortran_env,仅:real32、real64隐式无真实(真实64):: qk64真实(真实32):: qk32qk64 = 21909779.0_real64qk32 = qk64写( *, * ) 'qk64 = ', qk64写( *, * ) 'qk32 = ', qk32写( *, * ) '64 间距', 间距( qk64 )写( *, * ) '32 间距', 间距( qk32 )结束程序 one_outian@eris:~/work/stack$ gfortran -Wall -Wextra -fcheck=all -std=f2008 one_out.f90one_out.f90:11:9:qk32 = qk641警告:在 (1) [-Wconversion] 处从 REAL(8) 到 REAL(4) 的转换值可能发生变化ian@eris:~/work/stack$ ./a.outqk64 = 21909779.000000000qk32 = 21909780.064间距3.7252902984619141E-00932 间距 2.00000000
这里最重要的教训是,总是使用隐式无 - 第二个是编译器警告很有用,打开它们并找出它们的含义!
I'm translating a code from Fortran. I get a weird behavior during assignment. I know that adding the code could be very helpful but I can't add the exact code (I'm not authorized) and I was not successful to replicate it.
The lines are the following (qk was predefined and qk1 was not):
print*,"qk",qk
print*,"qk1",qk1
QK1=QK
print*,"qk",qk
print*,"qk1",qk1
and I get these values printed:
qk 21909779.000000000
qk1 6.44842193E+32
qk 21909779.000000000
qk1 21909780.0
The point is that I would expect to get qk1 equal to qk... why are they different? When I try to replicate it, obviously I get the same values printed.
Since I didn't add the code I do not expect a precise answer... does anyone have any idea about what to check?
The reason is that as indicated in the comments qk is single precision, qk1 double, and at the values required the spacing between single precision reals is 2:
Program one_out
Use, Intrinsic :: iso_fortran_env, Only : real32, real64
Implicit None
Real( real64 ) :: qk64
Real( real32 ) :: qk32
qk64 = 21909779.0_real64
qk32 = qk64
Write( *, * ) 'qk64 = ', qk64
Write( *, * ) 'qk32 = ', qk32
Write( *, * ) '64 spacing ', Spacing( qk64 )
Write( *, * ) '32 spacing ', Spacing( qk32 )
End Program one_out
ian@eris:~/work/stack$ gfortran -Wall -Wextra -fcheck=all -std=f2008 one_out.f90
one_out.f90:11:9:
qk32 = qk64
1
Warning: Possible change of value in conversion from REAL(8) to REAL(4) at (1) [-Wconversion]
ian@eris:~/work/stack$ ./a.out
qk64 = 21909779.000000000
qk32 = 21909780.0
64 spacing 3.7252902984619141E-009
32 spacing 2.00000000
The most important lesson here is always, always use Implicit None - and the second is that compiler warning are useful, turn them on and work out what they mean!
这篇关于赋值后的真实值与真实表达式不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!