精度不被尊重 [英] Precision not respected
问题描述
我将Visual Studio(2010 SP1)与Fortran IMSL(2011)结合使用时,无法获得符合我的实际情况的正确精度:
I use Visual Studio (2010 SP1) with Fortran IMSL (2011) and I can't get the right precision for my reals:
program prova
use, intrinsic :: iso_fortran_env
implicit none
integer, parameter :: ikind=selected_real_kind(p=8, r=99)
real(kind=ikind) :: a=0.79
real(real64) :: b=0.79
real(kind=16) :: c=0.79
real(8) :: d=0.79
print *, a
print *, b
print *, c
print *, d
end program prova
给我相同的结果: 0.790000021457672
(一个精度更高,一个精度更低,但是每个数字都与分配的数字不同:0.79)
give me the same result: 0.790000021457672
(one with more precision, one with less precision but every number is different from the assigned one: 0.79)
为什么我的意愿得不到尊重?
Why my willingness is not respected?
如何将所有实数设置为所需的精度?
How can I set all reals to the needed precision?
注意:我的问题与计算机的有限性质",四舍五入数字和类似数字无关.我的问题与Fortran中变量的类型/种类有关.
NB: my problem has nothing to do with the "limited nature of computer", roundoff numbers and similar. my problem regards type/kind of variable in Fortran.
推荐答案
您正在将变量设置为具有所需的精度,然后以默认精度分配常量.试试:
You are setting the variables to have the desired precision, but then assign constants with default precision. Try:
program prova
use, intrinsic :: iso_fortran_env
implicit none
integer, parameter :: ikind=selected_real_kind(p=8, r=99)
real(kind=ikind) :: a=0.79_ikind
real(real64) :: b=0.79_real64
real(kind=16) :: c=0.79_16
real(8) :: d=0.79_8
print *, a
print *, b
print *, c
print *, d
end program prova
这将以正确的精度设置常量,但是由于您仅提供两个有效数字,因此结果仍将舍入到最接近的可表示浮点数(以2为底). 0.79
可以精确地用十进制表示(以10为基数),而不能以2表示.您应该阅读有关浮点数的Wikipedia文章,当然,还应该是每个计算机科学家应了解的浮点运算法则.
This will set the constants in the correct precision, but since you only provide two significant digits, the result will still be rounded to the nearest representable floating point number (in base 2). 0.79
can be represented exactly in the decimal system (base 10), but not in base 2. Hence the deviations. You should read the Wikipedia Artical on Floating-Point Numbers and, of course, What Every Computer Scientist Should Know About Floating-Point Arithmetic.
这将导致
0.79000000000000004
0.79000000000000004
0.790000000000000000000000000000000031
0.79000000000000004
在我的机器上.
这篇关于精度不被尊重的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!