Fortran计算浮点数总和未获得精确的精度 [英] Fortran calculate sum of floating numbers not getting exact precision

查看:100
本文介绍了Fortran计算浮点数总和未获得精确的精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Fortran90的新手,我编写了一个简单的程序来添加两个浮点数,如下所示:

I am new to Fortran90 , I have write a simple program to add two floating point numbers as follows:

program Numbers_sum

  implicit none

  REAL :: sum
  sum = 1.6+2
  print*,"Sum =", sum
  end

我得到的答案是 Sum = 3.5999999

为什么没有得到 3.6 .我如何使该程序获得确切答案?任何帮助将不胜感激.

Why it is not getting 3.6. How Can I make this program to get the exact answer?? Any help will be appreciated.

推荐答案

无法在以2为底的有限数字中编写3.6.它是 2 +1 + 1/2 + 1/16 + ...

There is no way to write 3.6 in base 2 with finite digits. It's 2 + 1 + 1/2 + 1/16 + ...

但是,您可以通过选择适当的格式来隐藏舍入错误:

You can, however, hide the rounding error by selecting proper formatting:

write(*, '(F11.6)') sum

如果要以更高的精度进行计算,可以使用以下方法:

If you want to calculate in higher precision, you could use this:

REAL(KIND=8) :: var

或者,如果您想变得真正地正确:

Or, if you want to be really proper:

program numbers_sum
  implicit none
  integer, parameter :: dp = selected_real_kind(P=12)
  real(kind=dp) :: sum1
  sum1 = 1.6_dp + 2
  print *, "Sum = ", sum1
end

但是即使这样也不能完全消除舍入.

But even this won't eliminate the rounding completely.

欢呼

这篇关于Fortran计算浮点数总和未获得精确的精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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