在 Fortran90 中将较低精度的数字分配给较高的精度 [英] Assigning a lower precision number to a higher precision in Fortran90

查看:18
本文介绍了在 Fortran90 中将较低精度的数字分配给较高的精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于在 Fortran90 中分配文字的几个问题.使用 gfortran 4.6.

A few questions regarding assigning literals in Fortran90. Using gfortran 4.6.

程序:

program scratch
  implicit none
  integer, parameter :: RP = selected_real_kind(15)
  real(kind=RP) :: w,x,z
  real :: y

  w=2.2_RP
  x=2.2
  y=2.2
  z=2.125

  print*, w
  print*, x
  print*, y
  print '(F25.23)', y
  print*, z
end program scratch

输出:

   2.2000000000000002     
   2.2000000476837158     
   2.20000005    
   2.20000004768371582031250
   2.1250000000000000  

对于每个打印输出,我想了解编译器/处理器在做什么.例如.y 显示小数点后 7 位,但如果我们格式化输出,这些其他数字是从哪里来的?它们似乎与将默认的 real 文字 2.2 分配给更高的精度时发生的相同,kind=RP real<代码>x.那么文字是否被转换为以 2 为底,然后改变精度,或者类似的东西?

For each of the printouts I'd like to understand what the compiler/processor is doing. E.g. y is displayed with 7 digits after the decimal point, but if we format the output, where are these other digits coming from? They seem like they're the same ones that occur when a default-real literal 2.2 is assigned to a higher precision, kind=RP real x. So are the literals being converted to base 2, then changing precision afterwards, or something like that?

推荐答案

我们来看看对y的赋值.它是一个单精度变量,您为其分配一个单精度值.十进制值转换为使用的浮点表示,在大多数平台上是 IEEE 单精度,一种二进制浮点类型.这有 23 位小数、8 位指数和一个符号位.因为 2.2 不能以二进制浮点数精确表示,所以您会得到最接近(希望)的可表示值.

Let's look at the assignment to y. It is a single-precision variable and you assign a single-precision value to it. The decimal value is converted to the floating point representation used, which on most platforms is IEEE single precision, a binary floating point type. This has 23 bits of fraction, 8 bits of exponent and a sign bit. Because 2.2 isn't exactly representable in binary floating point, you get the closest (hopefully) representable value.

当您打印到更多位置时,那些其他数字"是转换为十进制的单精度值 - 因为它不是十进制的精确值,它往往有额外的非零数字.有些实现会给你合理数量的额外数字,有些可能会在一段时间后开始给你零,有些可能只是给随机数字.

Those "other digits" when you print to more places are the single precision value converted to decimal - since it isn't exact in decimal it tends to have additional non-zero digits. Some implementations will give you a reasonable number of additional digits, some might start to give you zeroes after a while, and some might just give random digits.

2.125 可以精确表示为二进制浮点数,因此可以在两个方向上精确转换.

2.125 is exactly representable in binary floating point, so it can be exactly converted in both directions.

这篇关于在 Fortran90 中将较低精度的数字分配给较高的精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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