不尊重精度 [英] Precision not respected

查看:25
本文介绍了不尊重精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 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 Artical on Floating-Point Numbers,当然还有 每位计算机科学家都应该了解的浮点运算知识.

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屋!

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