提高由整数商定义的变量的精度 [英] Improve precision on variables defined by integer quotient

查看:150
本文介绍了提高由整数商定义的变量的精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下程序:

 程序derp 
隐式无
整数,参数: :ikind = selected_real_kind(18)
real(kind = ikind):: a = 2.0 / 3.0
print *,a
结束程序derp

程序 derp 输出 0.6666666865348815917 ,这显然不是18位数的精度。但是,如果我使用相同的方法和定义 a = 2.0 b = 3.0 ,那么 define c = a / b 我得到的输出是 0.666666666666666666685 ,这很好。我怎样才能定义一个变量作为整数的商,并让它存储来自 selected_real_kind

解决方案

尝试: real(kind = ikind):: a = 2.0_ikind / 3.0_ikind



原因在于,LHS的精度很高,代码示例中的RHS不是2.0 / 3.0。 Fortran以单精度进行计算,然后将结果分配给LHS。由于LHS的精度很高,因此RHS一侧的计算精度并不高。 digits_kind 是指定常量类型的方法 digits


Say I have the following program:

program derp
    implicit none
    integer, parameter :: ikind = selected_real_kind(18)
    real (kind = ikind) :: a = 2.0 / 3.0
    print*, a
end program derp

The program derp outputs 0.6666666865348815917, which is clearly not 18 digits of precision. However, if I define a=2.0 and b=3.0 using the same method and then define c=a/b I get an output of 0.666666666666666666685, which is good. How do I just define a variable as a quotient of integers and have it store all the digits of precision I want from selected_real_kind?

解决方案

Try: real (kind = ikind) :: a = 2.0_ikind / 3.0_ikind

The reason is while the LHS is high precision, the RHS in your code example, 2.0 / 3.0, is not. Fortran does that calculation in single precision and then assigns the result to the LHS. The RHS side isn't calculated in higher precision because the LHS is high precision. digits_kind is the way of specifying the type of a constant digits.

这篇关于提高由整数商定义的变量的精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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