Real data type fortran 90

可紊 提交于 2019-12-11 14:25:28

问题


A simple question. A similar question was there, but I did not get the exact one I am looking for.

I was just checking the limits of real data type in fortran 90 (using ifort compiler), reason being my actual code might reach that limit. To test, I simply gave a parameter mval1 (see code) and multiplied by 2. In ifort manual it says that the maximum value it can take is 10E38 and my value is much smaller than this. But while printing it is taking random digits towards the end (output is given at the bottom). Could anyone help me through this

PROGRAM TEST

  IMPLICIT NONE
  REAL(KIND=8), PARAMETER :: mval1 = 1073E12
  REAL(KIND=8) :: j
  j = real(2*mval1)
  PRINT *, j,mval1

END PROGRAM TEST

Output

 2.146000005234688E+015  1.073000002617344E+015

回答1:


Two points to add to the commentary you've already had.

One: In Intel Fortran real(kind=8) variables are the same as IEEE-754 double precision numbers, and the maximum positive value is 1.797693134862316E+308. For single precision IEEE floating-point numbers, Intel Fortran real(kind=4), the maximum value is 3.4028235E+38 which is approximately your 10E38.

Two: Your declaration

REAL(KIND=8), PARAMETER :: mval1 = 1073E12

assigns a value of default real kind to mval1. I don't know what your default compiler settings are but check what happens if you change that line to

REAL(KIND=8), PARAMETER :: mval1 = 1073E12_8

which explicitly declares that the literal is of kind=8.

The answer to the question you don't quite ask, and which you are not quite given by the other comments is: floating-point arithmetic is tricky and programmers who would use it ought to familiarise themselves with at least the basic tricks. The Wikipedia article on floating-point numbers and arithmetic is a good starting point for your self-education. Whatever anyone else tells you ignore Goldberg's paper What every computer scientist should know about floating-point arithmetic until you start trying to implement your own floating-point numbers and arithmetic.



来源:https://stackoverflow.com/questions/24769095/real-data-type-fortran-90

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!